简体   繁体   English

jQuery-如何将选择限制为克隆元素的子代?

[英]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:

<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 . 现在加入新的节点我想要的东西的名称DOM之前,所以我需要选择.fname ,并非所有有文件中,但那些(在这种情况下,1)是内myitem

So I want to tell jQuery, select elements with a class of foo in the scope of my variable . 所以我想告诉jQuery, 我的变量范围内选择具有foo类的元素 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 ie 有两种方法,一种是在返回的对象上使用find()方法,另一种是使用jQuery函数的第二个参数,即

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

$variable.find( selector ); should do the trick, assuming it's a jQuery object. 假设它是jQuery对象,应该可以解决问题。

$('.foo', myitem)

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

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