简体   繁体   English

jQuery触发“ a”标签的点击事件

[英]jquery trigger click event for 'a' tag

i am trying to trigger a click event for anchor tag inside 'li'. 我试图触发“ li”内锚标记的click事件。 when click on 'li', i want to trigger a tag inside that 'li'. 当单击“ li”时,我想触发该“ li”中的标签。 my html and jQuery given below. 我的html和jQuery在下面给出。 below jquery showing this error. 下面的jQuery显示此错误。

"too much recursion .." “太多的递归..”

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


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

please help me. 请帮我。 thanks 谢谢

use the trigger event! 使用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. 发生相应事件时,将触发附加有.on()或其快捷方式之一的任何事件处理程序。 They can be fired manually, however, with the .trigger() method. 但是,可以使用.trigger()方法手动将其触发。 A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user 调用.trigger()会按照与用户自然触发事件的顺序相同的顺序执行处理程序

jQuery Trigger Event jQuery触发事件

Use 'find' instead of 'children' 使用“查找”而不是“孩子”

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

Call event.stopPropagation() to call click recursively as clicking the a will trigger the click for its parent li. 调用event.stopPropagation()以递归调用click,因为单击a将触发其父li的单击。 This will again cause the click of anchor tag which results in recursive call. 这将再次导致点击锚标记,从而导致递归调用。

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();         
      });
  });

Add this in your code: 在您的代码中添加:

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

This will prevent the click event to propagate from child element a to parent element li. 这将防止click事件从子元素a传播到父元素li。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM