trigger body click with jQuery

2019-06-17 01:33发布

I'm unable trigger a click on the body tag using jQuery, I'm using this...

$('body').click();

even this fails

$('body').trigger('click');

Any ideas?!

5条回答
我命由我不由天
2楼-- · 2019-06-17 01:52

interestingly.. when I replaced

$("body").trigger("click")

with

jQuery("body").trigger("click")

IT WORKED!!!

查看更多
叛逆
3楼-- · 2019-06-17 01:53

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.

查看更多
▲ chillily
4楼-- · 2019-06-17 01:58

I've used the following code a few times and it works sweet:

$("body").click(function(e){
  //you can then check what has been clicked
  var target = $(e.target);  
  if (target.is("#popup")) { }
}); // Added ); this for correct syntax
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-06-17 02:11

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.

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:

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.

查看更多
对你真心纯属浪费
6楼-- · 2019-06-17 02:15

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');
查看更多
登录 后发表回答