2010-06-01 40 views
3

我有一個Jstree擁有很多節點,其中一些具有相同的ID。如何選擇每個節點保存相同的ID

我想知道,我該如何做到這一點,如果有人選擇
其中一個節點,它會選擇每個節點具有相同的ID。

我試圖與

onselect: function (node) { 

工作,但我不知道究竟是什麼做的,
再加上我不知道如何手動選擇節點
(因爲它是所有做選擇:屬性)

+0

相同的ID不是一個好的做法.... – Reigel 2010-06-01 07:43:49

+0

你的意思是':selected'屬性嗎?在這種情況下,如果只適用於'

回答

3

IDs must be unique within the document,所以我假設你需要這樣做,因爲你從某處獲取數據並需要清理它。如果可以,請修復問題的根源。

但是,如果您不能,則可以遍歷樹中的元素以查找匹配的ID;是這樣的:

var theTargetID = /* ...whatever ID you're looking for... */; 
$(theTree).find("*").each(function(element) { 
    if (this.id == theTargetID) { 
     // it matches the ID 
    } 
}); 

這將創建一個潛在的巨大的臨時陣列(匹配樹的所有後代元素)。這可能是一個你最好使用枯燥的老式DOM遍歷而不是jQuery的漂亮包裝的地方,因爲你試圖用無效的文檔結構(多個ID)做一些事情。

這裏的原始DOM遍歷尋找目標ID可能是什麼樣子:

function traverse(theTargetID, element) { 
    var node; 

    if (element.id == theTargetID) { 
     // It matches, do something about it 
    } 

    // Process child nodes 
    for (node = element.firstChild; node; node = node.nextSibling) { 
     if (node.nodeType === 1) { // 1 == Element 
      traverse(theTargetID, node); 
     } 
    } 
} 

這假定element說法實際上是一個DOM元素(不是jQuery對象,或文本節點等。 )。它檢查元素的id,然後在必要時遞歸處理其子元素。這可以避免創建一個潛在的大型數組。

請注意,我一直指的是樹節點,而不是它內部的葉子。當樹被加載時,不僅當樹內的節點被選擇時,你想這樣做一次  —因爲你想盡可能簡短地具有無效結構並主動修復它。

+0

一些好主意,但是如果重複的id存在於作爲節點祖先的節點上呢? – 2010-06-01 09:30:37

+0

@Erik:我會更新它,我假設OP指的是具有'node'的樹節點,但我懷疑我錯了。謝謝。 – 2010-06-01 09:35:48

0

A T.J Crowder已經說過,ID在文檔中必須是唯一的。我認爲如果有重複的ID,你可能會在jsTree中產生一個非常奇怪的效果,所以我建議你做下面的事情。

對於您點擊的每個節點,在下面的示例中將id屬性的值存儲在var nodeId中。示例代碼會爲您找到重複的var nodeId。如果您發現重複項,則除第一個找到的節點外,其他所有節點都應將該ID更改爲唯一的ID。您可以通過將i的值或隨機文本字符串附加到該ID來完成此操作。

這就是我現在能爲你做的。如果您可以向我們提供一些更爲詳細的信息(HTML和您當前的Javascript代碼),那將有所幫助。

var nodeId = 'the-node-id'; // The id of your node id here. 
$('#' + nodeId).each(function() { 
    var matchingIds = $('[id='+this.id+']'); // May find duplicate ids. 
    if (matchingIds.length > 1 && matchingIds[0] == this) { 
    // Duplicates found. 
    for (i = 0; i < matchingIds.length; i++) { 
     // Whatever you like to do with the duplicates goes here. I suggest you give them new unique ids. 
    } 
    } 
}); 

更新:這是一種替代解決方案,其中重複的ID是頁面加載後直接發現,類同T.J克勞德的建議。

$('[id]').each(function() { // Selects all elements with ids in the document. 
    var matchingIds = $('[id='+this.id+']'); // May find duplicate ids. 
    if (matchingIds.length > 1 && matchingIds[0] == this) { 
    // Duplicates found. 
    for (i = 0; i < matchingIds.length; i++) { 
     // Whatever you like to do with the duplicates goes here. I suggest you give them new unique ids. 
    } 
    } 
});