Javascript $('body').on('click', '.anything', function(){})

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11921450/
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-24 07:40:22  来源:igfitidea点击:

$('body').on('click', '.anything', function(){})

javascriptjqueryhtml

提问by fancy

$('body').on('click', '.anything', function() {
    //code
});

doesn't work for anything right now and I can't figure out why. I'm able to anchor to anything else, say I just toss a #wrapdiv right inside the body. Then I'm able to do

现在对任何事情都不起作用,我不知道为什么。我可以锚定到其他任何东西,比如说我只是#wrapbody. 然后我就可以了

$('#wrap').on('click', '.anything', function() {
    //code
});

for any element I want.

对于我想要的任何元素。

Any idea what I could have done to disable this ability on the body element?

知道我可以做些什么来禁用 body 元素的这种能力吗?

Thanks!

谢谢!

回答by Syed Arif Iqbal

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

你应该使用$(document). 它是文档中任何点击事件的函数触发器。然后在里面你可以使用 jquery on("click","body *",somefunction),其中第二个参数指定要定位的特定元素。在这种情况下,身体内的每个元素。

$(document).on('click','body *',function(){
    //  $(this) = your current element that clicked.
    // additional code
});

回答by blasteralfred Ψ

If you don't want $('body').on('click'function, just change the function to $('#some_div_id').on('click'. If you want to stretch that div through body (100% height and width), then Hereis a demo.

如果您不需要$('body').on('click'函数,只需将函数更改为$('#some_div_id').on('click'. 如果您想通过主体(100% 高度和宽度)拉伸该 div,那么是一个演示。

Note: the demo has a 20% padding to body.

注意:演示中有 20% 的填充到正文。

回答by Codegiant

You can try this:

你可以试试这个:

You must follow the following format

您必须遵循以下格式

    $('element,id,class').on('click', function(){....});

*JQuery code*

* JQuery 代码*

    $('body').addClass('.anything').on('click', function(){
      //do some code here i.e
      alert("ok");
    });

回答by LmC

If you want to capture click on everything then do

如果你想捕捉点击一切然后做

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

我将它用于选择器:http: //api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

这用于处理点击:http: //api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

然后使用http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

停止正常的点击动作。