JavaScript 或 jQuery 中是否有任何方法可以检测事件何时完成传播 DOM?我有一个 jQuery 点击处理程序,它在点击时附加(带有目标“html”),并且一旦它冒泡到目标,添加它的点击就会触发它。我想延迟处理程序附件,直到传播完成。我听说 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");
}
});