附加的图片作为按钮,用来显示标题下的内容。
<!DOCTYPE html>
<html>
<body>
<h2>
the heading
</h2>
<p>
the content
</p>
</body>
</html>
$(document).ready(function () {
var $imag = $("<img src='arrow_down.jpg'>");
var $imag2 = $("<img src='arrow_up.jpg'>");
$("h2").append($imag);
$($imag).on("click", function(){
$("p").hide();
($imag).remove();
$("h2").append($imag2);
});
$($imag2).on("click", function () {
$("p").show();
($imag2).remove();
$("h2").append($imag);
});
});
$(document).main(ready);
一开始,图片被点击后还能用,但下次点击时,不用刷新页面就不能用了。为什么会这样?
这是因为像click()这样的事件处理程序必须附加到页面加载时已经在DOM中的元素上。对于后来添加的元素,必须使用on()从静态父元素中委托事件,比如。
$(document).on("click", $imag, function(){
$("p").hide();
($imag).remove();
$("h2").append($imag2);
});
$(document).on("click", $imag2, function () {
$("p").show();
($imag2).remove();
$("h2").append($imag);
});
刚刚添加了一个 小提琴 因为我不确定这是否能与变量$imag $imag2一起工作(它不能)。相反,你应该为你的图片添加类,比如像这样。
var $imag = $("<img class='down' src='arrow_down.jpg'>");
var $imag2 = $("<img class='up' src='arrow_up.jpg'>");
调整后的代码
$(document).on("click", '.down', function(){
$("p").hide();
$('.down').remove();
$("h2").append($imag2);
});
$(document).on("click", '.up', function () {
$("p").show();
$('.up').remove();
$("h2").append($imag);
});
供参考。https:/api.jquery.comon#on-events-selector-data-handler。,"直接和委托事件 "部分。
"事件处理程序只与当前选定的元素绑定;当你的代码调用.on()时,它们必须存在于页面上。"