2011-10-31 69 views
7

我做了一個非常簡單的按鈕單擊事件處理程序,我想有按鈕時按下<p>元素被追加,你可以檢查my code here關於jQuery的追加()以及如何檢查元素是否已被追加

<div id="wrapper"> 
    <input id="search_btn" value="Search" type="button"> 
</div> 
$("#search_btn").click(function(){ 
    $("#wrapper").append("<p id='other'>I am here</p>"); 
}); 

我有兩個問題問:

1,爲什麼我.append()如我所料不工作(這是追加<p>元素)

2. jQuery中,如何檢查,如果某個元素已追加?例如如何檢查<p id="other">是否已經附加在我的情況?

-------------------- update ------------------------ -------------------

請檢查my updated code here

因此,只有第二個問題依然存在,

+2

jsfiddle默認爲加載MooTools。我經常忘記改變它。 –

+0

自閉標籤不處理附加功能。儘管你可以使用.next() –

回答

22
  1. 您正在使用mootools而不是jQuery。

  2. 要檢查,如果你的元素存在

if($('#other').length > 0)

所以,如果你不想元素兩次追加:

$("#search_btn").click(function() { 
    if($('#other').length == 0) { 
     $("#wrapper").append("<p id='other'>I am here</p>"); 
    } 
}); 

或者,你可以使用.one(function) [ doc]:

$("#search_btn").one('click', function() { 
    $("#wrapper").append("<p id='other'>I am here</p>"); 
}); 
4

1)的jsfiddle加載默認情況下MooTools的,你需要包括jQuery的這個工作。世界上沒有理由爲什麼這個例子不起作用。 (假設$實際上映射到jQuery對象,即。)

2)可以檢查DOMElementnextSibling,或使用next() jQuery的方法,像這樣:

if(!$('#something').next().length) { 
    //no next sibling. 
} 
+0

做到這一點。澄清1:小提琴沒有加載jQuery庫,但是它是一個mootools。這一個工程:http://jsfiddle.net/j36ye/16/ – Lekensteyn

1

你的小提琴使用的是moo工具框架。將其更改爲在左側使用jquery框架並且它可以工作。見http://jsfiddle.net/KxGsj/

2

http://jsfiddle.net/j36ye/17/

$("#search_btn").click(function(){ 
    if(($('#other').length) == 0) { 
     $("#wrapper").append("<p id='other'>I am here</p>"); 
    } 
    return false 
}); 

或者

var other_appended = false; 

$("#search_btn").click(function(){ 
    if(other_appended == false) { 
     $("#wrapper").append("<p id='other'>I am here</p>"); 
      other_appended = true; 
    } 
    return false; 
}); 
2

如何檢查元素是否存在:

if($("p#other").length > 0) { 
    // a p element with id "other" exists 
} 
else { 
    // a p element with id "other" does not exist 
} 
1

檢查,如果元件已經附加:

alert($(this).parent().length?'appended':'not appended');