关于jQuery append()以及如何检查元素是否已被追加

Mel*_*lon 11 javascript jquery javascript-events

我做了一个非常简单的按钮点击事件处理程序,我希望<p>在点击按钮时附加元素,你可以在这里查看我的代码:

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

我有两个问题要问:

1,为什么我的.append()工作没有像我预期的那样(这是附加<p>元素)

2.在jQuery中,如何检查是否已经附加了一些元素?例如,如何检查是否<p id="other">已经附加在我的情况下?

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

在此处查看我的更新代码.

所以,只有第二个问题仍然存在......

Sam*_*iew 27

  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>");
    }
});
Run Code Online (Sandbox Code Playgroud)

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

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