jQuery how to execute event only on the inner element

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 17:16:44

The live method in jQuery works via event delegation, which is the act of catching all the bubbled events from individual elements onto a common ancestor (in your case its document).

Stopping the propagation/bubbling of the click event occurs on the handler element (which is the common ancestor, not on the element itself) and exists way above the li that you are trying to avoid.

So by the time the stopPropagation method gets called, we've already traversed down the dom and passed the li element.

It's essentially putting a stop sign 200ft after the intersection.

So you'll either need to use bind and stopPropagation or find a different solution.

Here is an example of what I'm talking about: http://jsbin.com/ibuxo (check the console)

you can see the code or edit it at http://jsbin.com/ibuxo/edit

My suggested solution to this problem would be to use bind instead of live.

This requires you to do a little bit extra work, but it's not so bad.

You are probably using live because you are adding new elements, and you want them to have the same functionality. You should do this by binding them when you input them to the page. Here's an example

$(function(){
  var myAnchorHandler = function(e){
    alert('clicked!');
    e.stopPropagation();
    return false;
  };

  // initial bind
  $('#somelist li a').click(myAnchorHandler);

  // code where you input more li elements to the list with links
  $('#somelist').append(
    // bind your function to the element now, and then append it
    $('<li><a>hi</a></li>').find('a').click(myAnchorHandler).parent()
  );
});
Eric Leschinski

Solution from Author:

I added all the a tags like above, so no mixup with live anymore.

$(markers).each(function(i,marker){
    listitem = $("<li />") 
    .html("Location ") 
    .click(function(e){
        showLocation(marker, i);
    })
    .appendTo("#somelist");
    $("<a />")
    .html("<strong>"+ids[i]+"</strong>")
    .addClass('ol id')
    .click(function(){
        $('#ginfo').show();
        return false;
    })
    .appendTo(listitem);

Here is an interesting page to explain event bubbling: How to stop event bubbling with jquery live?

Have the handler for the <a> tags return false.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!