Pregunta

The code below is working

$(function () {
    $('.bigDiv input:checkbox').click(function () {
        alert('working');
    });
});

But this one is not working

var checkboxes = $('.bigDiv input:checkbox');
$(function () {
    checkboxes.click(function () {
        alert('working');
    });
});
¿Fue útil?

Solución

Chances are that you have to put this line:

var checkboxes = $('.bigDiv input:checkbox');

inside the $(function () { block so the document is ready before you run that previous line of code. If the document isn't done loading, then there won't be any checkboxes to find. The point of $(function () { /* code here */}); is to wait until the document is done loading before running the code in the callback function.

You should be able to do it like this:

$(function () {
    var checkboxes = $('.bigDiv input:checkbox');
    checkboxes.click(function () {
        alert('working');
    });
});

Or alternately, you could just put this code in a script tag at the end of the body and not even need the ready handler:

var checkboxes = $('.bigDiv input:checkbox');
checkboxes.click(function () {
    alert('working');
});

Otros consejos

This is probably because you have your code in <head> or at least before your checkboxes are created. The following code:

$(function () {
});

Is short for

$(document).ready(function () {
});

Which attaches a function to be fired when the DOM is ready to be used (ie. the checkboxes are loaded). You should include all initialization stuff in your document ready function because you will be sure that the DOM has loaded.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top