开发者

jquery - How to limit selection to children of a cloned element?

I have an array of names:

var names = ['john', 'ted', 'pam'];

in the document I have this div:

<div id="template">
  Name: <input type="text" class="fname" />
  Age: <input type="text" class="age" />
</div>

for each name in the array I want to create inputs for name and age and pre-fill name. in the loop I am doing this:

var myitem = $('#template').clone().removeAttr('id');

Now before adding 开发者_运维问答the new nodes to the dom I want to stuff the name, so I need to select .fname, not all that there is in the document, but those (in this case 1) that is inside myitem.

So I want to tell jQuery, select elements with a class of foo in the scope of my variable. How do I do that?


There are two ways, one is to use the find() method on the returned object, the other is to use the second argument to the jQuery function i.e.

var firstWay=myitem.find(".foo");
var secondWay=$(".foo", myitem);


$('.foo', myitem)


$variable.find( selector ); should do the trick, assuming it's a jQuery object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜