Using .each on dynamic objects in jQuery?

别等时光非礼了梦想. 提交于 2019-12-12 09:28:33

问题


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>



回答5:


What about this:

http://jsfiddle.net/cudts0f2/

I want the dynamically generated text to take effect on each



来源:https://stackoverflow.com/questions/17451616/using-each-on-dynamic-objects-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!