2012-01-04 64 views
1

我有一個JavaScript樹,用戶選擇一個樹節點並單擊一個按鈕,然後在該選定的樹節點旁邊添加一個圖標。檢查元素或html標記是否存在

這裏是一個節點在該樹中的源代碼:

<li node_id="4" name="mars" > 
<ins class="jstree-icon"> </ins> 
<a href="#" class="jstree-clicked"><ins class="jstree-icon"> </ins> Mars Planet 
    <a style="cursor: default;"><ins class="pattern-icon3"> </ins></a> <!--this line displays the icon--> 
    <a style="cursor: default;"><ins class="pattern-icon3"> </ins></a> <!--this line displays the same icon again--> 
</a> 
</li> 
. 
. 
. 

下面是我使用追加旁邊的樹節點的圖標的代碼。

$j("li[name='"+node_name+"'] > a").append('<a style="cursor:default;"><ins class="' + icon_class + '">&nbsp;</ins></a>'); 

圖標顯示正確。

我的問題是:

我需要一次只能顯示特定圖標。 當前,當用戶選擇一個節點並點擊兩次按鈕時,將在該選定節點旁邊附加2個圖標。

在添加之前,有沒有方法檢查節點名稱旁邊是否已附加<a style="cursor: default;"><ins class="pattern-icon3"> </ins></a>

+1

與這個問題無關,但這種''的使用並不是真正的語義。如果你想要一個風格化的連字符/減號,*使用連字符*。 – You 2012-01-04 16:44:46

+1

非常感謝您的建議,但我使用Jstree從json文件生成樹,並且標記由jstree本身創建。 – tanya 2012-01-04 16:53:09

回答

2

你可以試試元素與find()匹配並將其附加只有在比賽失敗:

var listItemLink = $j("li[name='" + node_name + "'] > a"); 
if (!listItemLink.find("." + icon_class).length) { 
    listItemLink.append('<a style="cursor:default;"><ins class="' 
     + icon_class + '">&nbsp;</ins></a>'); 
} 
+0

正是我想要的,歡呼! – tanya 2012-01-04 17:02:11

1

您可以嘗試選擇.pattern-icon3元素並檢查產生的對象的length屬性。如果該元素不存在,則length將爲0。如果它確實存在,這將是大於0

if($j("li[name='" + node_name + "'] > a .pattern-icon3").length) { 
    //Already exists! 
} 
+0

感謝您的建議 – tanya 2012-01-04 17:01:56

2

如果你想檢查HTML是否存在:

if ($('#selector').length > 0){ 
    alert('tag exists'); 
} 
1

只是一個想法,但也許你可以使用.one

$("li[node_id]").one("click", function() { 
    // show the icon 
});