2

JavaScript 或 jQuery 中是否有任何方法可以检测事件何时完成传播 DOM?我有一个 jQuery 点击处理程序,它在点击时附加(带有目标“htm​​l”),并且一旦它冒泡到目标,添加它的点击就会触发它。我想延迟处理程序附件,直到传播完成。我听说 event.stopPropagation() 是有风险的业务,所以我宁愿不使用它。

这是我的代码。#title-editable 是一个锚标记。vclick 是由 jQuery Mobile 定义的事件。我只需单击#title-editable 即可获得两个控制台日志。

  $("#title-editable").on("vclick", function(event){
    event.preventDefault();
    console.log("First handler fired.");
    /* Would like to detect completion of event propagation here 
      and only execute the next statement after that. */
    $("html").one("vclick",function(){
      console.log("Second handler fired.");
    });
  });

编辑:我想我有一个解决方法。而不是 .one 用于内部事件,我使用 .on 因此事件在第一次触发时不会分离。我检查点击事件的目标,只对内部事件执行更改,如果目标不是#title-editable,则分离内部事件。

  $("#title-editable").on("vclick", function(event){
    event.preventDefault();
    console.log("First handler fired.");
    $("html").on("vclick",function(event2){
      console.log("Second handler fired.");
      if(!$(event2.target).closest("#title-editable").length){
        console.log("Execute changes here.");
        $("html").off("vclick");
      }
    });
4

1 回答 1

0

根据您的最后评论,最简单的逻辑是这样的:

var changed=false;
$('#title-editable').on('vclick',function(event){
    event.preventDefault();
    console.log("First handler fired.");
    changed=true;
});
$(document).on("vclick",function(){
    if(changed){
        console.log("Second handler fired.");
        //here you can revert your actions and then the next line
        changed=false;
    }
});

更新:

第二种理论:

您说祖先在单击时会获得一个类,#title-editable因此您可以尝试以下代码:

$(document).on("vclick",function(event){
    if($('#title-editable').parent().hasClass('givenClass')){ //assuming the class is called "givenClass" and the ancestor is the parent of "#title-editable" (you need to sort that out)
        console.log("Second handler fired.");
        //here you can revert your actions and then the next line
    }
    else{
        event.preventDefault();
        console.log("First handler fired.");
    }
});

第三种理论:

$(document).on("vclick",function(event){
    if(!$('#title-editable').is(':visible')){
        console.log("Second handler fired.");
        //here you can revert your actions and then the next line
    }
    else{
        event.preventDefault();
        console.log("First handler fired.");
    }
});

第四种理论:

$(document).on("vclick",function(event){
    if(!$('#title-editable').is(event.target) || !$('#title-editable').has(event.target)){
        console.log("Second handler fired.");
        //here you can revert your actions and then the next line
    }
    else{
        event.preventDefault();
        console.log("First handler fired.");
    }
});
于 2014-09-21T19:02:47.220 回答