jQuery $(document).on("click"... 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17605296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:23:54  来源:igfitidea点击:

$(document).on("click"... not working?

jqueryclick

提问by Mr. Lavalamp

Is there a well-known mistake I could be making here?

我可能在这里犯了一个众所周知的错误吗?

I've got a script that's using .on() because an element is dynamically generated, and it isn't working. Just to test it out, I replaced the selector with the dynamic element's wrap, which is static, and it still didn't work! When I switched to plain old .click for the wrap it worked, though.
(This just won't work for the dynamic element obviously, the one that matters.)

我有一个使用 .on() 的脚本,因为一个元素是动态生成的,但它不起作用。只是为了测试一下,我用动态元素的 wrap 替换了选择器,这是静态的,但它仍然不起作用!不过,当我切换到普通的旧 .click 进行包装时,它起作用了。
(这显然不适用于动态元素,重要的元素。)

This works:

这有效:

$("#test-element").click(function() {
    alert("click");
});

This doesn't:

这不会:

$(document).on("click","#test-element",function() {
    alert("click");
});

UPDATE:

更新:

I right-clicked and did "Inspect Element" in Chrome to just double-check something, and then after that the click event worked. I refreshed and it didn't work, inspected element, and then it worked. What does this mean?

我右键单击并在 Chrome 中执行“检查元素”以仔细检查某些内容,然后单击事件起作用。我刷新了但它不起作用,检查了元素,然后它起作用了。这是什么意思?

回答by itsmejodie

You are using the correct syntax for binding to the document to listen for a click event for an element with id="test-element".

您正在使用正确的语法绑定到文档来侦听 id="test-element" 元素的点击事件。

It's probably not working due to one of:

由于以下原因之一,它可能无法正常工作:

  • Not using recent version of jQuery
  • Not wrapping your code inside of DOM ready
  • or you are doing something which causes the event not to bubble up to the listener on the document.
  • 不使用最新版本的 jQuery
  • 未将您的代码包装在 DOM 中
  • 或者您正在做一些导致事件不会冒泡到文档上的侦听器的事情。

To capture events on elements which are created AFTERdeclaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.

要捕获在声明事件侦听器创建的元素上的事件 - 您应该绑定到父元素或层次结构中更高的元素。

For example:

例如:

$(document).ready(function() {
    // This WILL work because we are listening on the 'document', 
    // for a click on an element with an ID of #test-element
    $(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
    });

    // This will NOT work because there is no '#test-element' ... yet
    $("#test-element").on("click",function() {
        alert("click bound directly to #test-element");
    });

    // Create the dynamic element '#test-element'
    $('body').append('<div id="test-element">Click mee</div>');
});

In this example, only the "bound to document" alert will fire.

在此示例中,只会触发“绑定到文档”警报。

JSFiddle with jQuery 1.9.1

JSFiddle 与 jQuery 1.9.1

回答by smilebomb

Your code should work, but I'm aware that answer doesn't help you. You can see a working example here (jsfiddle).

您的代码应该可以工作,但我知道答案对您没有帮助。你可以在这里看到一个工作示例(jsfiddle)

Jquery:

查询:

$(document).on('click','#test-element',function(){
    alert("You clicked the element with and ID of 'test-element'");
});

As someone already pointed out, you are using an ID instead of a class. If you have more that one element on the page with an ID, then jquery will return only the first element with that ID. There won't be any errors because that's how it works. If this is the problem, then you'll notice that the click event works for the first test-elementbut not for any that follow.

正如有人已经指出的那样,您使用的是 ID 而不是类。如果页面上有多个具有 ID 的元素,则 jquery 将返回具有该 ID 的第一个元素。不会有任何错误,因为它就是这样工作的。如果这是问题所在,那么您会注意到 click 事件适用于第一个,test-element但不适用于后续的任何事件。

If this does not accurately describe the symptoms of the problem, then perhaps your selector is wrong. Your update leads me to believe this is the case because of inspecting an element then clicking the page again and triggering the click. What could be causing this is if you put the event listener on the actual documentinstead of test-element. If so, when you click off the document and back on (like from the developer window back to the document) the event will trigger. If this is the case, you'll also notice the click event is triggered if you click between two different tabs (because they are two different documents and therefore you are clicking the document.

如果这不能准确描述问题的症状,那么您的选择器可能是错误的。你的更新让我相信这是因为检查一个元素然后再次点击页面并触发点击。可能导致这种情况的原因是,如果您将事件侦听器放在实际document而不是test-element. 如果是这样,当您单击文档并重新单击时(例如从开发人员窗口返回文档),该事件将触发。如果是这种情况,您还会注意到如果您在两个不同的选项卡之间单击,则会触发 click 事件(因为它们是两个不同的documents,因此您正在单击文档。

If neither of these are the answer, posting HTML will go a long way toward figuring it out.

如果这些都不是答案,那么发布 HTML 将大有帮助。

回答by Sulung Nugroho

An old post, but I love to share as I have the same case but I finally knew the problem :

一个旧帖子,但我喜欢分享,因为我有同样的案例,但我终于知道了问题所在:

Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.

问题是:我们创建了一个函数来处理指定的 HTML 元素,但尚未创建与此函数相关的 HTML 元素(因为该元素是动态生成的)。为了使它工作,我们应该在创建元素的同时创建函数。元素优先于与它相关的函数。

Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.

简单地说,一个函数只对在它之前创建的元素(他)起作用。任何动态创建的元素都意味着在他之后。

But please inspect this sample that did not heed the above case :

但是请检查这个没有注意上述情况的样本:

<div class="btn-list" id="selected-country"></div>

Dynamically appended :

动态附加:

<button class="btn-map" data-country="'+country+'">'+ country+' </button>

This function is working good by clicking the button :

通过单击按钮,此功能运行良好:

$(document).ready(function() {    
        $('#selected-country').on('click','.btn-map', function(){ 
        var datacountry = $(this).data('country'); console.log(datacountry);
    });
})

or you can use body like :

或者你可以使用 body 像:

$('body').on('click','.btn-map', function(){ 
            var datacountry = $(this).data('country'); console.log(datacountry);
        });

compare to this that not working :

与此相比不起作用:

$(document).ready(function() {     
$('.btn-map').on("click", function() { 
        var datacountry = $(this).data('country'); alert(datacountry);
    });
});

hope it will help

希望它会有所帮助

回答by iGanja

This works:

这有效:

<div id="start-element">Click Me</div>

$(document).on("click","#test-element",function() {
    alert("click");
});

$(document).on("click","#start-element",function() {
    $(this).attr("id", "test-element");
});

Here is the Fiddle

这是小提琴

回答by Eduárd Moldován

Try this:

尝试这个:

$("#test-element").on("click" ,function() {
    alert("click");
});

The document way of doing it is weird too. That would make sense to me if used for a class selector, but in the case of an id you probably just have useless DOM traversing there. In the case of the id selector, you get that element instantly.

这样做的文档方式也很奇怪。如果用于类选择器,这对我来说是有意义的,但在 id 的情况下,您可能只有无用的 DOM 遍历那里。对于 id 选择器,您可以立即获得该元素。