jquery 触发 'a' 标签的点击事件

jquery trigger click event for 'a' tag

我正在尝试为 'li' 内的锚标记触发点击事件。单击 'li' 时,我想在 'li' 中触发一个标签。我的 html 和 jQuery 下面给出。下面 jquery 显示此错误。

"too much recursion .."

<li><a href="link">link text</a></li>


$(document).ready(function(){
 $("#menu-top li").click(function(){
  $(this).children('a').click();
 });
});

请帮帮我。谢谢

使用'find'代替'children'

$(document).ready(function(){
 $("#menu-top li").click(function(){
  $(this).find('a').click();
 });
});

调用 event.stopPropagation() 递归调用 click,因为单击 a 会触发其父级 li 的单击。这将再次导致单击锚标记,从而导致递归调用。

Live Demo

  $(document).ready(function () {
      $("#menu-top li").click(function (event) {
          alert("li clicked");
          $(this).children('a').click();       
      });
      $("#menu-top li a").click(function (event) {
          //your code
          alert("a clicked");
          event.stopPropagation();         
      });
  });

在您的代码中添加:

$("#menu-top li a").click(function(e){
 e.stopPropagation();
});

这将阻止点击事件从子元素 a 传播到父元素 li。

使用trigger事件!

<li><a href="link">link text</a></li>

$(document).ready(function(){
 $("#menu-top li").click(function(){
  $(this).children('a').trigger('click');
 });
});

Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user

jQuery Trigger Event