Javascript 使用JQUERY选择带有.on(';change';)事件的动态插入的Div元素

Javascript 使用JQUERY选择带有.on(';change';)事件的动态插入的Div元素,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试向Select添加一个.on('change')事件,该事件是动态插入行的一部分。console.log(数据)正在返回正确的数据集。我不知道如何让它在激活select的同一行上选择#prototypePrice $(document).ready(function() { $('#lineitems').on('change', '.prototypeSelect', function() { var that = $(this); $

我正在尝试向Select添加一个
.on('change')
事件,该事件是动态插入行的一部分。
console.log(数据)正在返回正确的数据集。我不知道如何让它在激活select的同一行上选择
#prototypePrice

    $(document).ready(function() { 
    $('#lineitems').on('change', '.prototypeSelect', function() {  
        var that = $(this); 
    $.get('getItem.php?q=' + $(this).val(), function(data) { 
        console.log(data);      
        var objItem = jQuery.parseJSON(data);  
        that.closest('#prototypePrice').val(objItem.item_price); //this is wrong

      });
   });
});
以下是原型行:

 <div style="display:none;" id="rowPrototype" >                                     
 <div>
      <select id="prototypeSelect" class="prototypeSelect">

     //Select Options

      </select>
 </div>
 <div>
    <input type="text" id="prototypePrice" class="prototypePrice">
    </input>
    </div>
 </div

//选择选项

最近的
遍历DOM树并获得第一个匹配的祖先

在您的情况下,要设置值的输入是div的子级,该div是
that

因此,您可以使用:

that.closest('div').next().find('.prototypePrice').val(objItem.item_price);
而不是:

that.closest('#prototypePrice').val(objItem.item_price);

选中:,

它是更改的select的下一个同级的子项,因此

$(document).ready(function () {
    $('#lineitems').on('change', '.prototypeSelect', function () {
        var that = $(this);
        $.get('getItem.php?q=' + $(this).val(), function (data) {
            console.log(data);
            var objItem = jQuery.parseJSON(data);
            that.parent().next().find('.prototypePrice').val(objItem.item_price); //this is wrong
        });
    });
});
演示:

还请注意,如果重复给定的结构,则不应对这些元素使用
id
,因为它将创建重复的id


另外,
input
是一个自动关闭元素,因此没有

您可以为每一行使用唯一的id。这样,使用该id进行搜索就更容易了

$('#'+rowID+“.prototypePrice”).val(newValue)

您可以使用行上下文

$(".prototypePrice",that.parents('#rowPrototype')).val(newVal)
如果“prototypePrice”重复,请与arun达成一致,然后不要将其用作id。也可以使用Prototype。它应该被用作类

$(".prototypePrice",that.parents('.rowPrototype')).val(newVal)

做一个工作摆弄一些选择,这将很容易帮助谢谢你,正是我所寻找的。小提琴也很有用。
$(".prototypePrice",that.parents('.rowPrototype')).val(newVal)