用 jQuery 触发身体点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/919725/
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
trigger body click with jQuery
提问by ruturaj
I'm unable to trigger a click on the body tag using jQuery using this:
我无法使用 jQuery 触发对 body 标签的点击:
$('body').click();
Even this fails:
即使这失败了:
$('body').trigger('click');
回答by ruturaj
Interestingly, when I replaced this:
有趣的是,当我替换它时:
$("body").trigger("click")
With this:
有了这个:
jQuery("body").trigger("click")
It works!
有用!
回答by kgiannakakis
You should have something like this:
你应该有这样的事情:
$('body').click(function() {
// do something here
});
The callback function will be called when the user clicks somewhere on the web page. You can trigger the callback programmatically with:
当用户单击网页上的某处时,将调用回调函数。您可以通过以下方式以编程方式触发回调:
$('body').trigger('click');
回答by Fermin
I've used the following code a few times and it works sweet:
我已经多次使用以下代码,它运行良好:
$("body").click(function(e){
// Check what has been clicked:
var target = $(e.target);
if(target.is("#target")){
// The target was clicked
// Do something...
}
});
回答by Seeker
if all things were said didn't work, go back to basics and test if this is working:
如果所有事情都说不起作用,请回到基础并测试这是否有效:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$('body').click(function() {
// do something here like:
alert('hey! The body click is working!!!')
});
</script>
</body>
</html>
then tell me if its working or not.
然后告诉我它是否有效。
回答by Alexis Wilke
As mentioned by Seeker, the problem could have been that you setup the click()
function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.
正如 Seeker 所提到的,问题可能是您click()
过早地设置了该功能。从您的代码片段中,我们无法知道您放置脚本的位置以及它是否在正确的时间运行。
An important point is to run such scripts after the document is ready. This is done by placing the click()
initialization within that other function as in:
重要的一点是在文档准备好后运行此类脚本。这是通过将click()
初始化放置在其他函数中来完成的,如下所示:
jQuery(document).ready(function()
{
jQuery("body").click(function()
{
// ... your click code here ...
});
});
This is usually the best method, especially if you include your JavaScript code in your <head>
tag. If you include it at the very bottom of the page, then the ready()
function is less important, but it may still be useful.
这通常是最好的方法,尤其是当您在<head>
标签中包含 JavaScript 代码时。如果您将它包含在页面的最底部,那么该ready()
功能就不那么重要了,但它可能仍然有用。