如何防止jQuery事件冒泡到父元素?

时间:2021-05-16 14:30:29

I have a series of nested UL's that are like this:

我有一系列嵌套的UL认证是这样的:

<ul class="categorySelect" id="">
  <li class="selected">Root<span class='catID'>1</span>
    <ul class="" id="">
      <li>First Cat<span class='catID'>2</span>
        <ul class="" id="">
          <li>cat in First<span class='catID'>3</span>
            <ul class="" id="">
            </ul>
          </li>
          <li>another cat in first<span class='catID'>4</span>
            <ul class="" id="">
            </ul>
          </li>
        </ul>
      </li>
      <li>cat in root<span class='catID'>5</span>
        <ul class="" id="">
        </ul>
      </li>
    </ul>
  </li>
</ul>

I then have jQuery that I intended to move the "selected" class to different LIs on click():

然后我有了jQuery,我打算在click()中将“选择”类移动到不同的LIs:

$(document).ready(function () {

    $("ul.categorySelect li").click(function () {
        $("ul.categorySelect li.selected").removeClass("selected");
        $(this).addClass("selected");
    })

});

When I tested this, at first it didn't appear to be working at all. I added an alert("click") inside the click event function and I was able to tell that it was working, but the click event registered on both the child LI and parent LIs which meant that ultimately the root LI would always end up as selected.

当我测试这个时,起初它似乎根本就不工作。我在click事件函数中添加了一个警告(“click”),我可以知道它正在工作,但是在子LI和父LIs上都注册了click事件,这意味着最终root LI将始终以选中的方式结束。

Is there a way to prevent the click() event from executing on parent LIs?

是否有一种方法可以防止click()事件在父LIs中执行?

1 个解决方案

#1


8  

Use event.stopPropagation(); the link provides an example.

使用event.stopPropagation();链接提供了一个示例。

#1


8  

Use event.stopPropagation(); the link provides an example.

使用event.stopPropagation();链接提供了一个示例。