[英]About jQuery append() and how to check if an element has been appended
我做了一個非常簡單的按鈕點擊事件處理程序 ,我想在點擊按鈕時附加<p>
元素,你可以在這里查看我的代碼 :
<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">
是否已經附加在我的案例中?
--------------------更新----------------------------- --------------
所以,只有第二個問題仍然存在......
你正在使用mootools而不是jQuery。
檢查您的元素是否存在
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>");
});
1)默認情況下,jsFiddle在MooTools中加載,你需要包含jQuery才能工作。 世界上沒有理由為什么這個例子不起作用。 (假設$
實際上映射到jQuery
對象,那就是。)
2)您可以檢查DOMElement
的nextSibling
,或使用next()
jQuery方法,如下所示:
if(!$('#something').next().length) {
//no next sibling.
}
檢查元素是否已經附加:
alert($(this).parent().length?'appended':'not appended');
$("#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;
});
如何檢查元素是否存在:
if($("p#other").length > 0) {
// a p element with id "other" exists
}
else {
// a p element with id "other" does not exist
}
你的小提琴正在使用moo工具框架。 將其更改為使用左側的jquery框架,它可以正常工作。 見http://jsfiddle.net/KxGsj/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.