简体   繁体   English

将事件添加到DOM之前,将其单击事件添加到jQuery对象

[英]click event to a JQuery object before adding it to the DOM

Attaching the click event to a JQuery object before adding it to the DOM is done like this I believe. 我相信,在将click事件添加到DOM之前,将click事件附加到JQuery对象是这样完成的。

 $('.Button').on('click', '#Your-Selection', function () {
 console.log("yeahhhh!!! but this doesn't work for me :(");
 });

Is there a way to attach it to a span child of #Your-Selection. 有没有一种方法可以将其附加到#Your-Selection的span子代中。 This does not work but something like: 这不起作用,但是类似:

 $('.Button').on('click', '#Your-Selection span', function () {
 console.log("yeahhhh!!! but this doesn't work for me :(");
 });

Please use like this 请这样使用

$(document).on('click', '#Your-Selection span', function () {
  console.log("yeahhhh!!! this will work for you :)");
});

this will attach click event to the span child of #Your-Selection 这会将点击事件附加到#Your-Selection的span子级

I think you are not asking the right question, please take a look at the jquery on method documentation: http://api.jquery.com/on/ 我认为您不是在问正确的问题,请查看方法文档中的jquery: http : //api.jquery.com/on/

If neither .Button exists (on DOM load) is better to attach it to the body, but if it exists is better attach to body that the whole document, or the closest tag you have in DOM 如果两个按钮都不存在(在DOM加载时),最好将其附加到主体,但如果存在,则最好将整个文档或您在DOM中拥有的最接近的标记附加到主体。

You should do something like this: 您应该执行以下操作:

$("body").on("click", ".Button #Your-Selection span", function(){
  //whatever you want
});

As per the jQuery API documentation I have doubts with below solutions. 根据jQuery API 文档,我对以下解决方案有疑问。 The correct way I think is like as follows: 我认为正确的方法如下:

$('#Your-Selection').on('click','span',function(){
    console.log('yeahhhh!!! this will work');
});

so if the button is inside the span you can modify the above code as follow 因此,如果按钮在范围内,则可以按以下方式修改上面的代码

$('#Your-Selection').on('click','span .Button',function(){
    console.log('yeahhhh!!! this will work');
});

So the event only need to be bubble up one level. 因此,事件只需要向上泡沫即可。 If you use document or body event need to bubble up so many levels if your HTML structure is complex. 如果您使用documentbody事件,并且您的HTML结构复杂,则需要将其扩展到多个级别。

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

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