【问题标题】:how to click an anchor tag from javascript or jquery如何从 javascript 或 jquery 中单击锚标记
【发布时间】:2015-08-14 10:35:19
【问题描述】:

有一个锚标记,试图从 javascript 中单击它但没有响应,在加载页面时它应该转到 next.php 而无需手动单击锚标记。我该如何存档?

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="jquery-2.0.3.js"></script>
    <script type="text/javascript">
         alert("hai");
         $(document).ready(function() { $('#about').click(); });             
    </script>
</head>   
<body>
    <div>
         <a href="next.php" id="about">click here</a>
    </div>
</body>
</html>

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    使用$('selector')[0],因为$('selector') 返回一个jQuery 对象,所以$('selector').click() 将触发点击处理程序,而$('selector')[0].click() 将触发实际点击。

    $(document).ready(function () {
        $('#about')[0].click();  //$('#about').get(0).click();
    });
    

    Demo

    【讨论】:

    • 我知道为什么[0] 在id 之后吗? get(0) 是什么?
    • get(0)[0] 相同。 为什么[0]id 之后因为- $('#about') 返回一个 jQuery 对象。因此,如果已定义,则单击此事件将触发 jQuery 单击处理程序。 $('#about')[0] 将返回一个 javascript 对象,click() 将模拟实际点击。
    • 它对我有用。无论如何,我无法理解“将触发点击处理程序,而 ***** 将触发实际点击”的概念。
    • @ShaunakD 感谢兄弟搜索了很长时间
    【解决方案2】:

    你不能使用javascript来触发点击事件

    应该使用

    <script type="text/javascript">
           $(document).ready(function() { 
                 document.location.href='/next.php'
           });
    </script>
    

    【讨论】:

    【解决方案3】:

    这里是可以帮助你的代码

    $(document).ready(function() {
    
    
      $(document).ready(function() {
        $('a').trigger('click');
      });
    
    })
    
    function abc() {
      alert("");
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" onclick="abc()">click me not</a>

    如果您想要推荐的方式,请在 $(document).ready 中使用它

    window.location="where ever you want to go";
    

    【讨论】:

      【解决方案4】:

      如果您希望页面无需点击即可转到next.php,请将window.location 直接放入$(document).ready(function() { });

      Click()函数用于触发点击事件。 IE。当您想在单击锚标记时触发某些操作时。

      <script>
         alert("hai");
         $(document).ready(function() { 
            window.location = 'next.php';  //If you wish the page to automatically go to next page on page load.
            $('#about').click(   // If you wish to do something clicking anchor
              function(){
                 alert("Hello");
              }); 
            });
      </script>
      

      【讨论】:

        【解决方案5】:
        $(document).ready(function() { $('#about').trigger('click'); });
        

        更新:

         $(document).ready(function() {  $('#about')[0].click(); });
        

        【讨论】:

        • 这段代码无响应,显示正常,点击后才进入下一页。
        猜你喜欢
        • 2013-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多