jquery:双击功能
问题描述:
为什么我点击“关闭”div,不显示“基本文本”?总之,为什么不工作第二个“点击”功能?jquery:双击功能
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#sp").click(function(){
$("#info").html("<div><div id='close'>Close</div><div>new text</div></div>");
});
$("#close").click(function(){
$("#info").html("<div>basic text</div>");
});
});
</script>
<style>
</style>
</head>
<body>
<p id="sp">Click</p>
<div id="info">
<div>basic text</div>
</div>
</body>
</html>
答
您将需要此功能live()
:
$("#sp").click(function(){
$("#info").html("<div><div id='close'>Close</div><div>new text</div></div>");
});
$("#close").live('click', function(){
$("#info").html("<div>basic text</div>");
});
单击事件处理程序已连接(更不要在这种情况下)后,将创建你的id为closed
元素。您需要确保它也会附加到动态创建的元素。为此,您可以使用live()
答
事件冒泡,因此您可以直接在info
上放置一个处理程序,该程序寻找点击ID为close
的元素。
$(document).ready(function(){
$("#sp").click(function(){
$("#info").html("<div><div id='close'>Close</div><div>new text</div></div>");
});
$("#info").click(function(e){
if(e.target.id === "close") {
$(this).html("<div>basic text</div>");
}
});
});
作为替代方案,您可以使用delegate()
(docs),它基本上是一样的东西。
$(document).ready(function(){
$("#sp").click(function(){
$("#info").html("<div><div id='close'>Close</div><div>new text</div></div>");
});
$("#info").delegate('#close','click',function(e){
$(this).parent().html("<div>basic text</div>");
});
});
最终,最好的解决办法是让所有的页面上的标记加载时,只是show()
(docs)和hide()
(docs)它是必要的。这比销毁和重新创建可重用内容要好得多。
答
因为设置点击时关闭不存在。改用直播功能。
$("#close").live("click", function(){
$("#info").html("<div>basic text</div>");
});
答
因为close
元素是动态添加的,并且在页面加载时不存在于DOM中。
如果您修改代码一点,以:
$("#close").live('click',
function(){
$("#info").html("<div>basic text</div>");
});
它应该工作的罚款。
live()
允许将事件绑定到尚未在DOM中创建/呈现的元素。