无法使用jquery将事件处理程序附加到动态添加的输入字段

时间:2017-07-21 12:00:48

标签: javascript jquery html

我尝试根据输入字段值动态添加输入字段。添加字段后,我想在这些动态添加的输入字段上添加事件,这就是我所做的,但我没有得到我想要的结果。这是我尝试使用jquery的内容。

html文件:

<input class='cls1' id='num' />
<div id="samp"></div>

脚本文件

function add() {
    var num = $("#num").val()
    data = ""
    for (i = 0; i<num; i++) {
        var id_name = "input_" + i
        data += "<input class='cls2' id='" + id_name + "' /><br>"
    }
    $("#samp").show().html(data)
}

$(".cls1").on("change keyup paste", function (event) {
    console.log("chng1")
    // this's logging
    add() // this adds input fields
})

$(".cls2").on("change keyup paste", function (event) {
    console.log("chng2") // not logging
})

$("input[id^='input_']").on("change keyup paste", function (event) {
  console.log("chng2") // not logging
})

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

&#13;
&#13;
function add() {
    var num = $("#num").val()
    data = ""
    for (i = 0; i<num; i++) {
        var id_name = "input_" + i
        data += "<input class='cls2' id='" + id_name + "' /><br>"
    }
    $("#samp").show().html(data)
}

$(".cls1").on("change keyup paste", function (event) {
 
    // this's logging
    add() // this adds input fields
})

$("#samp").on("change keyup paste",'.cls2', function (event) {
    console.log("chng2") // not logging
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='cls1' id='num' />
<div id="samp"></div>
&#13;
&#13;
&#13;