Event listener not working on dynamically added el

2020-04-08 01:34发布

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.

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.

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

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

2条回答
该账号已被封号
2楼-- · 2020-04-08 01:49

Use this :

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

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.

Side note :

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.

查看更多
够拽才男人
3楼-- · 2020-04-08 01:57

try this

JS CODE

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

LIVE DEMO

查看更多
登录 后发表回答