如何访问复制到变量的div的子项

时间:2013-02-03 18:04:59

标签: javascript jquery

在我的网页上,我有一个类“编辑器”的DIV,我将其复制到变量中。

editorTemplate = $('.editor');

DIV看起来像这样(简化):

<div class="editor">
  <div>
    Title: <span class="title" id="title">  the title goes here  </span><br />
    <select class="recording_list" id="recording_list">
      <option value="1">Pos 1</option>
      <option value="2">Pos 2</option>
      ...
    </select>
</div>  <!-- class=editor -->

稍后我想通过将其添加到页面来创建该div的系列:

$(editArea).append(editorTemplate);

到目前为止一切顺利。

但是我想在将编辑器模板粘贴到页面上之前更改一些属性 - 比如字段的ID,一些文本和选项框的选定元素。

我可以用

更改编辑模板的ID
$(myEdit).attr("id", "edit" + nEditors);

但我不知道如何访问模板的INNER元素,例如“标题”字段的ID和文本。

将模板粘贴到页面后,我可以说

$('#title').attr("id", "title" + nEditors);
$('#title').html("the new text");
...

在将模板粘贴到页面之前是否可以进行这些更改?

4 个答案:

答案 0 :(得分:4)

您可以使用JQuery.children()方法。

var editorTemplate = $('.editor');
editorTemplate.children('<selectors to uniquely identify the child object>').<method to update the content accordingly>

那么我们可以做这样的事情......

count=1;
editorTemplate.children('span#title').html('<Update HTML here>').attr('id','title_'+count);

<强>更新

我刚注意到你的元素处于多个级别,因此使用.find()将是理想的,因为它可以遍历多个级别以选择后代元素(孙子等)。

答案 1 :(得分:4)

您没有将元素复制到变量中。

editorTemplate = $('.editor');

上面创建了一个jQuery包装器,其中包含一组指向DOM元素的指针。包装器允许您执行以DOM元素为目标的jQuery方法。

如果您执行editorTemplate.find("#title").attr("id", "newId"),则会更改您当前在DOM中指向的元素的id属性,而不是新副本。

当您计划稍后执行此操作时:

$(editArea).append(editorTemplate);

以上内容不会附加DOM元素的新副本,而是moving将您通过editorTemplate包装器指向的元素从DOM中的原始位置添加到新元素中DOM editArea正在引用。

如果您计划在editorTemplate中复制某些元素以便稍后添加它们,则可以使用jQuery clone(),类似于:

// use clone(true, true) to also clone any attached events
var editorTemplate = $('.editor').clone();

// Using .find you can change attribute in your new copy/clone
editorTemplate.find("#title").attr("id", "title" + nEditors).html("the new text");

// append your new copy/clone
$(editArea).append(editorTemplate);

答案 2 :(得分:1)

您可以使用find方法访问元素:

var editorTemplate = $('.editor');

$(editorTemplate).find('#title').attr('id', 'title' + nEditors).html('the new text');

答案 3 :(得分:1)

editorTemplate.clone()
              .attr({})
              .find("select").attr({id:"whatever"}).end()
              .find("span").....end()
              .appendTo($(editarea))

我希望你明白这个想法