Javascript 关于jQuery append()以及如何检查是否已追加元素
我制作了一个非常简单的按钮单击事件处理程序,我希望在单击按钮时添加Javascript 关于jQuery append()以及如何检查是否已追加元素,javascript,jquery,javascript-events,Javascript,Jquery,Javascript Events,我制作了一个非常简单的按钮单击事件处理程序,我希望在单击按钮时添加元素,您可以检查: $(“#搜索_btn”)。单击(函数(){ $(“#包装器”).append(我在这里”; }); 我有两个问题要问: 1,为什么我的.append()不能像我期望的那样工作(这就是append元素) 2.在jQuery中,如何检查是否已经附加了某些元素?例如,如何检查我的案例中是否已经添加了 --------------更新----------------------------------------
元素,您可以检查:
$(“#搜索_btn”)。单击(函数(){
$(“#包装器”).append(我在这里
”;
});
我有两个问题要问:
1,为什么我的.append()
不能像我期望的那样工作(这就是append
元素)
2.在jQuery中,如何检查是否已经附加了某些元素?例如,如何检查我的案例中是否已经添加了
--------------更新-------------------------------------------
请查收
因此,只剩下第二个问题了……1)默认情况下,在MooTools中加载JSFIDLE,您需要包含jQuery才能使其工作。世界上没有任何理由说明这个例子不起作用。(假设$
实际上映射到jQuery
对象,也就是说。)
2) 您可以检查domeElement
的nextSibling
,或者使用next()
jQuery方法,如下所示:
if(!$('#something').next().length) {
//no next sibling.
}
if($(“#其他”).length>0
因此,如果不想将元素追加两次:
$("#search_btn").click(function() {
if($('#other').length == 0) {
$("#wrapper").append("<p id='other'>I am here</p>");
}
});
你的小提琴正在使用moo工具框架。将其更改为使用左侧的jquery框架,它就可以工作了。请参见
$(“#搜索_btn”)。单击(函数(){
如果($(“#其他”).length=0){
$(“#包装器”).append(我在这里
”;
}
返回错误
});
或
var-other\u-added=false;
$(“#搜索_btn”)。单击(函数(){
if(其他附加==false){
$(“#包装器”).append(我在这里
”;
其他附加值=真;
}
返回false;
});
如何检查元素是否存在:
if($("p#other").length > 0) {
// a p element with id "other" exists
}
else {
// a p element with id "other" does not exist
}
检查元素是否已追加:
alert($(this).parent().length?'appended':'not appended');
jsiddle默认为加载MooTools。我也经常忘记更改它。自动关闭标签不处理附加功能。尽管您可以在1上使用.next()进行说明:fiddle不是加载jQuery库,而是加载mootools库。这一个有效:
$("#search_btn").one('click', function() {
$("#wrapper").append("<p id='other'>I am here</p>");
});
$("#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
}
alert($(this).parent().length?'appended':'not appended');