Jquery点击范围不起作用

时间:2017-10-08 23:57:56

标签: jquery html

  1. 完成整页后不会运行。我不知道为什么?
  2. 如何在完成加载整个页面时执行此操作我想运行onload函数。
  3. 谢谢大家。

    <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>

2 个答案:

答案 0 :(得分: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>

我希望它有所帮助

答案 1 :(得分:0)

最佳做法之一是将js代码放在结束</body>标记之前的底部,以便首先加载html然后通过js代码读取它,像这样:

如果您需要点击事件

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

如果您只想在页面加载时发出提醒

&#13;
&#13;
 <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>
&#13;
&#13;
&#13;