开发者

Trouble connecting click event to button in MooTools

开发者 https://www.devze.com 2023-04-12 19:07 出处:网络
I just downloaded MooTools 1.4.I\'m having trouble connecting a button click to the launching of an AJAX request.In my page below, I have a button with id=\"submit\", but clicking the button doesn\'t

I just downloaded MooTools 1.4. I'm having trouble connecting a button click to the launching of an AJAX request. In my page below, I have a button with id="submit", but clicking the button doesn't trigger the alert ...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
<script type="text/javascript" src="js/mootools-co开发者_如何学编程re-1.4.1-full-compat.js"></script>
<script type="text/javascript">
    /* ajax alert */
    $('submit').addEvent('click', function(event) {
        alert("hello");
        var filename = $('filename').value;
        //prevent the page from changing
        event.stop();
        //make the ajax call
        var req = new Request({
            method: 'get',
            url: '/renderhtml/' + filename,
            data: { },
            onRequest: function() { 
            // on request
        },
        onComplete: function(response) { 
            $('content').set('html',response);
        }
        }).send();
    }); 
</script>
</head>
<body>

    <div>
        <form name="f">
            File name: <input type="text" size="25" id="filename" name="filename" value="" />
            <input type="button" id="submit" name="submit" value="Submit" />
        </form>
    </div>
    <div id="content"></div>

</body>
</html>

I have confirmed the mootools source file is in the right place. What else am I missing? Thanks, - Dave


You should use the domready event on the window, or place the script tag below the button in the HTML. (preferably all the way down the body)

You're trying to access the button with id submit while the page is still loading, so the button doesn't exist yet. However, when you execute the code on the domready or maybe load event, you can be sure that the whole page is loaded and dom manipulation can be done.

window.addEvent('domready', function() {
  // Your code
});

^ waits for the page to load before it does anything.

0

精彩评论

暂无评论...
验证码 换一张
取 消