3

I have a textbox titled "Number of questions" where a user enters an integer. Whenever they enter a number, the following code is ran:

$('#dmc_mc_questionCount').keyup(function() {
    var amount = $(this).val();

    add_to = "";
    for(i = 0; i < amount; i++) {
       var current = i + 1;
       add_to = add_to + current + "<input type='input' name='data[Section][mc_answers][]' value='" + i +"' id='mc_answers_" + i + "' maxlength='1'> ";
    }

    $('#mc_answer_key').html(add_to); 
});

The following code works:

<span id="test">Test</span>

$('#test').click(function() {
    var x = $('#mc_answers_0').val();
    alert(x);
});

But the following does not:

$('#mc_answers_0').click(function() {
    alert('d');
});

Why can't I access #mc_answers_0?!

4

1 回答 1

2

事件委托:

$(document).on('click', '#mc_answers_0', function() {
    alert('d');
});

#mc_answers_0在 DOM 就绪时不存在,因此您的处理程序永远不会接受。

于 2013-06-15T00:41:40.640 回答