jquery嵌套li多次单击事件调用

我有以下结构。

  • Folder 1
    • Item 1.1
  • Folder 2
    • Subfolder 2.1
      • File 2.1.1
      • File 2.1.2
    • File 2.2
  • Folder 3 (closed at start)
    • File 3.1
  • File 4

在js我有以下function。

 $("#browser li").click(function(){ }); 

当我点击li File 2.1.1时。 该函数调用3次

第一次为li文件2.1.1,第二次为li子文件夹2.1,第三次为li文件夹2。

任何人都可以给我一个解决方案来调用该函数一次吗?

您的帮助非常适合。 谢谢。

那是因为你在#broswer下有很多 li元素。

试试这个:

 $("#browser>li").click(function(){ //only direct children of #browser //your code }); 

或者您可以使用event.stopPropagation()

 $("#browser li").click(function(event){ event.stopPropagation(); //your code }); 

将您的function更改为

 $("#browser li").click(function(event){ event.stopPropagation(); //do your other stuff }); 

这样,点击较低级别的li就不会“冒泡”到更高级别的li

这是因为事件事件会“冒泡”你的dom,所以如果你点击它

文件2.1.1,文件2.1和文件2也会听到它来修复此更改事件

 $("#browser li").click(function(e){ //Your code here e.stopPropagation(); }); 

而不是在li对象上使用click事件添加另一个元素(在示例范围内)并处理单击其中。 这种方式仍然可以为更高的事件冒泡,只是不会通过嵌套的li冒泡。

 //Run the following to see the no li bubble result $(".nobubble").on('click',function(){ $("#result").append($(this).attr("data-id") +"
") }); //uncomment the following to see the li bubble result /*$(".bubble").on('click',function(){ $("#result").append($(this).attr("data-id") +"
") });*/
  
  • a
    • b