i start a little web-project with .net MVC 3. My Problem: i included Jquery 1.8.3.js. But my functions doesnt work in the javascript files:

This isn´t working:

$(document).ready(function() {
    $('input:button').button();
});

$('#testbut').on('click', function (event, ui) {

    alert("CLICK");

});

this is still working fine:

$(document).ready(function() {
    $('input:button').button();

    $('#testbut').on('click', function (event, ui) {

    alert("CLICK");

    });
});

i have no idea why.

the include is in right order.

有帮助吗?

解决方案

The first example fails because the code is being executed as the page is being loaded and the elements it refers to haven't been loaded yet. This is also why the second example does work.

By placing your code in a document ready block it holds off executing it until the page has loaded.

其他提示

When you put blocks of code in $(document).ready(), it waits to attach listeners to the targets after the document has been loaded. So in your first example, jquery attaches the listener $('#testbut').on('click', function (event, ui) { but the DOM has not loaded the element yet. In the second example, it attaches the listener only after document is loaded.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top