事件侦听器不适用于动态添加的元素

事件侦听器不适用于动态添加的元素

问题描述:

我正在使用jQuery在按下提交按钮时向我的文档添加h1标记.我想稍后(通过单击鼠标)与此h1标签进行交互,因此我需要为其添加事件处理程序.但是,它似乎没有注册点击.

I'm adding, an h1 tag to my document when a submit button is pressed, using jQuery. I want to interact with this h1 tag at a later time (with mouse clicks), so I need to add an event handler to it. However, it does not seem to be registering the clicks.

我以前曾经在SO上问过这个问题,他们都说我使用了.on(),但是仍然没有运气.我也没有收到任何错误,所以也不知道从哪里开始.

I've seen this question asked on SO before and they all say use .on(), which I have, but still no luck. I'm not receiving any errors either so don't know where to begin.

以下是所有内容的非常简化版本的 jsFiddle .谢谢.

Here is the jsFiddle of a very simplified version of it all. Thanks.

$("h1").on("click", function(){
    alert("test");
    $("h1").css("color","red");
})

使用此方法:

$(document.body).on("click", "h1", function(){
    alert("test");
    $("h1").css("color","red");
})

当您在其上调用on时,jquery集必须包含将包含h1的元素.您可以将document.body替换为您确定h1所在的任何元素.

The jquery set must contain, when you call on on it, the elements that will contain the h1. You might replace document.body with any element in which you're sure the h1 will be.

旁注:

确定要不要使用$(this).css("color","red");而不是$("h1").css("color","red");吗?使用$(this)会更改单击的h1的颜色,而不是全部h1的颜色.

Are you sure you don't want $(this).css("color","red"); instead of $("h1").css("color","red"); ? Using $(this) would change the color of the clicked h1 and not all h1.