簡體   English   中英

關於jQuery append()以及如何檢查元素是否已被追加

[英]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">是否已經附加在我的案例中?

--------------------更新----------------------------- --------------

在此處查看我的更新代碼

所以,只有第二個問題仍然存在......

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

1)默認情況下,jsFiddle在MooTools中加載,你需要包含jQuery才能工作。 世界上沒有理由為什么這個例子不起作用。 (假設$實際上映射到jQuery對象,那就是。)

2)您可以檢查DOMElementnextSibling ,或使用next() jQuery方法,如下所示:

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

檢查元素是否已經附加:

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

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

如何檢查元素是否存在:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM