2013-02-03 35 views
4

在我的網頁上,我有一個類「編輯器」的DIV,我將其複製到變量中。如何訪問複製到變量的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); 

但我不知道如何訪問模板,例如內元素標題和「標題」字段的文本。

模板後粘貼到網頁,我可以說

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

是否有可能之前我貼模板到頁面中,使這些變化?

+0

'在我的網頁我有一個類的DIV「主編「我將其複製到一個變量中。」你不是在複製這些元素。您只是創建一個名爲'editorTemplate'的jQuery包裝器變量,它是一個指向與選擇器匹配的DOM元素的指針。這一點很重要,以後在做'append(editorTemplate)'時,你會最終移動DOM元素而不是複製新的版本。如果您想製作DOM元素的副本,請稍後操作它們並添加它們,對您希望製作的元素使用[** clone()**](http://api.jquery.com/clone/)副本。 – Nope

+0

非常感謝提示。 – PaulS

回答

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); 

UPDATE:

我只注意到你的元素是在多層次所以使用.find()會是理想的,因爲它可以遍歷多個層次來選擇後代元素(孫輩等)。

1

你凸輪使用find方法去你的元素的訪問權限:

var editorTemplate = $('.editor'); 

$(editorTemplate).find('#title').attr('id', 'title' + nEditors).html('the new text'); 
1
editorTemplate.clone() 
       .attr({}) 
       .find("select").attr({id:"whatever"}).end() 
       .find("span").....end() 
       .appendTo($(editarea)) 

我希望你的想法

4

您不會將元素複製到變量中。

editorTemplate = $('.editor'); 

上面創建了一個包含指向DOM元素的指針集的jQuery包裝器。包裝器允許你執行鍼對DOM元素的jQuery方法。

如果你這樣做editorTemplate.find("#title").attr("id", "newId")它改變了你當前在DOM中指向的元素的id屬性而不是新副本。

當你計劃後這樣做:

$(editArea).append(editorTemplate); 

以上不會追加的DOM元素的新副本,而是會moving再指出通過​​包裝從原來的位置的元素在DOM中的新位置editArea正在引用。

如果您打算內​​做一些元素的副本後追加它們,你可以使用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); 
+0

太棒了!在這麼短的時間內有這麼多的答案。我很感謝 – PaulS

+0

@ user2035236 - 通常很好的問題吸引了更多的眼球.. :) –

+0

非常感謝提示。我是一個完整的JS新手,並會做很多類似的錯誤,我想:) – PaulS

相關問題