在.html()之后找不到Jquery id

时间:2014-08-03 21:17:39

标签: javascript jquery html

我试图根据用户选择逐步显示表单元素。但是如果我选择多个答案选项,那么用.html()函数插入的select元素的id似乎找不到。

以下是关于小提琴的代码:http://jsfiddle.net/SdF4p/1/

HTML code:

     <form id="test">
        <select id="type_of_answer">
            <option selected disabled>Type of answer</option>
            <option value="single">Simple answer</option>
            <option value="multiple">Multiple answer</option>
            <option value="interval">Answer with interval</option>
        </select>
        <br><br>
        <div id="box1">

        </div>
        <div id="box2">

        </div>
    </form>

Jquery代码:

     var nb_answer = '<select id="nb_answer"><option selected disabled>Number of answer</option><option value="2">2</option><option value="3">3</option></select>';
     var single_answer = '<input id="single_answer" type="text" placeholder="Answer">';
     var multiple_answer1 = '<input id="answer1" type="text" placeholder="Answer 1"><br><input id="answer2" type="text" placeholder="Answer 2"><br><input id="answer3" type="text" placeholder="Answer3">';
     var multiple_answer2 = '<input id="answer1" type="text" placeholder="Answer 1"><br><input id="answer2" type="text" placeholder="Answer 2"><br>';
     var interval = '<input id="interval1" type="text" placeholder="Inf"><br><input id="interval2" type="text" placeholder="Sup">';



 $('#type_of_answer').change(function () {

$('#box2').html(''); //reset

if ($('#type_of_answer').val() == "single") {

    $('#box1').html(single_answer);

} else if ($('#type_of_answer').val() == "multiple") {

    $('#box1').html(nb_answer);

} else {

    $('#box1').html(interval);
}
      });


   $('#nb_answer').change(function () {**//the problem is here. It is clearly not executed**


if ($('#nb_answer').val() == "2") {

    $('#box2').html(multiple_answer1);

} else {

    $('#box2').html(multiple_answer2);
}
  });

1 个答案:

答案 0 :(得分:2)

由于您正在动态生成元素,因此需要使用.on()而不是.change():

$(document).on('change', '#nb_answer', function () {
    $('#box2').html('Bouger');
    if ($('#nb_answer').val() == "2") {
        $('#box2').html(multiple_answer1);
    } else {
        $('#box2').html(multiple_answer2);
    }
});

<强> jsFiddle example