如何将onclick回调附加到div,而不是在div内部的链接上



Html

<div class='item_container'>
[...bunch of links and pictures...]
<a class='item_owner'>John Doe</a>
</div>

Javascript

/**
    Bind the onclick only if you hover on the item since we got a lot
    of items and several events and plugins to setup on them.
*/
$('.item_container').live('mouseenter', function(e){
  $this = $(this);
  if (!$this.data('isSetup')) {
    $this.click(function(e){
      // do magic
      return false;
    });
     [... a lot of other stuff]
    $this.data({'isSetup': true});
  }
});

当然,当我点击div中的任何位置时,它都会执行"变魔术"。多亏了return false,如果我点击div中的任何链接,它仍然会执行"魔术",并且不会更改页面,这是预期的行为。

但有一个链接被认为是真正改变页面的,那就是所有者链接。问题是,以我目前的设置,我阻止它工作。

您需要停止从链接到父.item_container的事件传播。

将此块添加到代码中:

$('.item_container a.item_owner').live('click', function(e){
 e.stopPropagation();
});

最新更新