关于jQuery append()以及如何检查元素是否已附加 [英] About jQuery append() and how to check if an element has been appended
问题描述
我做了一个非常简单的 button click事件处理程序,我想在单击按钮时附加<p>
元素,您可以检查
I made a very simple button click event handler, I would like to have <p>
element be appended when button clicked, you can check my code here:
<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>
元素后面)
1, why my .append()
does not work as I expected (that's append the <p>
element)
2.在jQuery中,如何检查某些元素是否已附加?例如,如何检查<p id="other">
是否已经添加到我的案例中?
2. in jQuery, how to check if some element is already appended? For example how to check if <p id="other">
has already appended in my case?
--------------------更新----------------------- --------------------
请在此处检查我更新的代码.
所以,仅剩下第二个问题...
So, only the 2nd question remains...
推荐答案
-
您正在使用mootools,而不是jQuery.
You are using mootools and not jQuery.
检查元素是否存在
if($('#other').length > 0)
因此,如果您不想两次追加元素:
So if you do not want to append the element twice:
$("#search_btn").click(function() {
if($('#other').length == 0) {
$("#wrapper").append("<p id='other'>I am here</p>");
}
});
或者,您可以使用.one(function)
[文档]:
Or, you can use the .one(function)
[doc]:
$("#search_btn").one('click', function() {
$("#wrapper").append("<p id='other'>I am here</p>");
});
这篇关于关于jQuery append()以及如何检查元素是否已附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!