简体   繁体   English

jquery 设置 function 对每个动态添加的输入 id 做出反应并获取此输入 id 号

[英]jquery set function to react on every dynamically added input id and get this input id number

I dynamically add more input fields where orders id goes like this, orders1, orders2, orders3, etc.:我动态添加更多输入字段,其中订单 ID 如下所示,orders1、orders2、orders3 等:

html_code += '<input type="text" name="orders[]" id="orders'+count+'">';

now I have this code:现在我有这个代码:

$('#orders1 / 2 3').typeahead({ **//here I need to set to javascript react on all numbers dynamically**
 //mycode ...
 ordernumber = 1 / 2 3...; **//here I need to extract number**
 updater: function (obj) {
            var item = JSON.parse(obj);
            $('#orderitem' + ordernumber).val(item.tax);
            return item.name;
        }
});
  1. how should I set $('#orders1 / 2 3') to be able to react on every dynamically added input?我应该如何设置$('#orders1 / 2 3')以便能够对每个动态添加的输入做出反应?
  2. how can I get ordernumber to be able to set it up on line $('#orderitem' + ordernumber)?我怎样才能让ordernumber能够在 $('#orderitem' + ordernumber) 行上设置它?

A better option would be to add a class to all dynamic inputs and to get ordernumber set a data-* custom attribute like:更好的选择是将 class 添加到所有动态输入并获取ordernumber设置data-*自定义属性,例如:

html_code += '<input class="orders" data-number="'+ count +'" name="orders[]" id="orders'+count+'">';

and then you can apply typeahead to all of them like:然后您可以将typeahead应用于所有这些,例如:

$('.orders').each(function() {

  //here extract number
  var ordernumber = $(this).data('number');

  // here initialise typeahead
  $(this).typeahead({
    ....
  });
});

Edit:编辑:

Put this logic in a function like:将此逻辑放入 function 中,例如:

function reInit(){
    $('.orders').each(function() {

      //here extract number
      var ordernumber = $(this).data('number');

      // here initialise typeahead
      $(this).typeahead({
        ....
      });
    });
}

// Call the function initially
reInit();

and adding the elements dynamically and appending it to the dom call the function again.并动态添加元素并将其附加到 dom 再次调用 function。

html_code += '<input class="orders" data-number="'+ count +'" name="orders[]" id="orders'+count+'">';

// I don't know how are you adding the item to dom
// but something like
$(parent).append( html_code )

// Now call the function again
reInit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM