2017-10-08 69 views
0
  1. 当完成整个页面时,它不会运行。我不知道为什么?
  2. 我完成加载整个页面时我是如何做的,我想运行onload函数。

谢谢大家。Jquery点击范围不起作用

<html> 
 
         <head> 
 
         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
         </head> 
 
         <body> 
 
         <body> 
 
          <div> 
 
           <div><span id="exid">Hello</span></div> 
 
          </div> 
 
         </body> 
 
        <script> 
 
         window.onload = function() { 
 
          $('#exid').on('click', function(){ 
 
          alert('2'); 
 
          }); 
 
         }; 
 
         </script> 
 
        </html>

+0

当我运行代码片段(使用蓝色按钮“运行代码片段”)时,单击“Hello”标签确实会显示警告(预期行为)。所以有什么问题? –

+0

您是否需要加载警报(而不是点击)功能? – Anuresh

回答

0

我不能完全肯定,如果我明白你的意思,但我认为这可能是这...

<html> 
    <head> 
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
    </head> 
    <body> 
     <div> 
      <div><span id="exid">Hello</span></div> 
     </div> 
     <script> 
      $(document).ready(function() { 

       // This will be executed when you click in the span. 
       $('#exid').on('click',function() { 
        alert('2'); 
       }); 

       // If you want to execute the same code of the click when the page 
       // is loaded, you can just trigger the created click event. 
       $('#exid').trigger('click'); 
      }); 
     </script> 
    </body> 
</html> 

我希望它能帮助

0

其中一个最佳做法是将js代码放在底部</body>标签的底部,以便html首先加载然后通过你的js代码读它,像这样:

如果你想click事件

<html> 
 
<head></head> 
 
<body> 
 
    <span id="exid">Hello</span> 
 

 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    <script> 
 
    $(document).ready(function(){ 
 
     $('#exid').click(function(){ 
 
     alert('Clicked!'); 
 
     }); 
 
    }); 
 
    </script> 
 
</body>

如果你只是想报警时,页面加载速度

<html> 
 
    <head></head> 
 
    <body> 
 
     <span id="exid">Hello</span> 
 

 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
     <script> 
 
     $(document).ready(function(){ 
 
      alert('2'); 
 
     }); 
 
     </script> 
 
    </body>