简体   繁体   English

jQuery 单击处理程序仅触发一次

[英]jQuery click handler only fires once

Appended images used as buttons to show/hide content below a heading:附加图像用作按钮以显示/隐藏标题下方的内容:

<!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);

At first the images work when clicked.起初,图像在单击时起作用。 but the next time you click it, it doesn't without having to refresh the page.但是下次单击它时,不必刷新页面。 Why?为什么?

This is because event handlers like click() have to be appended to elements that are already in the DOM when the page is loaded.这是因为在加载页面时,必须将 click() 等事件处理程序附加到 DOM 中已经存在的元素。 For elements that are added later the event has to be delegated from a static parent element using on(), like:对于稍后添加的元素,必须使用 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);
});

Just added a Fiddle with an adjustment as I wasn't sure if this would work with the variables $imag / $imag2 (it doesn't).刚刚添加了一个带有调整的小提琴,因为我不确定这是否适用于变量 $imag / $imag2 (它没有)。 Instead you should just add classes to your images, eg like this:相反,您应该只为您的图像添加类,例如:

var $imag = $("<img class='down' src='arrow_down.jpg'>");
var $imag2 =  $("<img class='up' src='arrow_up.jpg'>");

with adjusted code调整后的代码

$(document).on("click", '.down', function(){
  $("p").hide();
  $('.down').remove();
  $("h2").append($imag2);
});
$(document).on("click", '.up', function () {
  $("p").show();
  $('.up').remove();
  $("h2").append($imag);
});

For reference: https://api.jquery.com/on/#on-events-selector-data-handler , section "Direct and delegated events":供参考: https : //api.jquery.com/on/#on-events-selector-data-handler ,“直接和委托事件”部分:

"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()." “事件处理程序仅绑定到当前选定的元素;在您的代码调用 .on() 时,它们必须存在于页面上。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM