Using .each on dynamic objects in jQuery?

2019-04-17 20:55发布

问题:

There are lots of questions that seem to be asking this, but in the end all they want is to attach .click events and not .each and so the generally accepted answer in all of them include $("body").on("click", ".selector", function(){}); and this is definitely not what I want.

I have some generated inputs and I need to change the value of each one at the same time. Normally I would $(".inputs").each(function(){$(this).val("new-value")}; or something along those lines, however, I can't because of the dynamic aspect.

So how would you do a $("body").on("each", ".inputs", function(){});?

回答1:

Actually, it's as simple as running the .each inside setTimout.

setTimeout(function(){
  $(".inputs").each(function(){$(this).val("new-value")});
}, 5000);


回答2:

$.each works with any new elements added.

http://jsfiddle.net/4SV7n/

Doing something different each time:

http://jsfiddle.net/4SV7n/1/



回答3:

You can use $(".inputs").each(function(){$(this).val("new-value")}; perfectly fine on dynamic elements. You just need to rerun the script after you added an element dynamically.

From the comments I figured that some misunderstanding exists about 'each'. 'Each' is not an event and so no event is fired if 'each' is called. If you want to keep track of added elements because you have no control over when they are added you'd need a timer:

setInterval(function(){ $(".inputs").each(function(){$(this).val("new-value")}; },500);


回答4:

Here is much better script that does exactly what the OP asked.

function doWithInput(i, e){
	$(e).val("done with each");
}

$(document).ready(function(){
    $("#button").click(function(){
       $("#inputs").append("<input class='inputs_new' type='text' /><br />");
    });
  	$(".inputs").each(doWithInput);
});

$(document).on("DOMNodeInserted", ".inputs_new", function(e) {
	$(e.target).removeClass('inputs_new').addClass('inputs');
  doWithInput(0, e.target);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputs">
    <input class="inputs" type="text" placeholder='type in me' /><br />
</div>
<button type="button" id="button">Add</button>