如何找到 javascript 事件的发起位置?
我有一个 JS 脚本,它创建了一个新节点并将其插入到 HTML 页面。我正在处理 DOM 突变事件,并且可以捕获 DOMNodeInserted 事件。在该函数内部,我想找出源(即在 HTML 的哪个部分调用了脚本函数)和目标(即在 HTML 页面中添加了节点)。
我可以使用 event.target
找到目标,但无法找到事件源。
例如,考虑以下伪代码 HTML 页面:
<html>
<head>
<script>
function test() {
//DOM access
<div_object>.setAttribute("attr", "value");
}
</script>
</head>
<body onload="test()">
<div id="123">
</div>
</body>
</html>
我希望我的源是 BODY(因为这是启动脚本的地方),目标应该是 div(123)(因为该属性被添加到 div_123。
我该如何做到这一点?
I have a JS script which created a new Node and inserts it to the HTML page. I am handling DOM mutation events and can capture DOMNodeInserted event. Inside that function I want to find out the source (i.e. in which part of the HTML has the script function been called) and the target (i.e. in which part the node is being added in the HTML page).
I am able to find the target using event.target
, but I am not able to find the source of the event.
For example, consider the following pseudocode HTML page:
<html>
<head>
<script>
function test() {
//DOM access
<div_object>.setAttribute("attr", "value");
}
</script>
</head>
<body onload="test()">
<div id="123">
</div>
</body>
</html>
I want my source to be BODY (because that is were the script is initiated), target should be div(123) (because the attribute is added to div_123.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
抱歉,您无法找出哪段代码导致事件被触发,它们是完全解耦的。您必须让触发代码进行协作,将其自己的
this
/event.target
值存储在变量中,以便触发代码稍后获取。但如果你们有这样的合作,就不需要 DOM 突变事件。
如果您有一个事件处理层(作为许多 JS 框架的一部分),您可以将
this
/target
跟踪放在该层中,因此触发的代码可能会询问“在我之前发生的最后一个事件是什么?”。但我不相信这值得。通常最好添加您自己的在组件之间进行通信的协作钩子;您通常不能依赖 DOM 突变事件,因为它们没有全局且完全受支持(或者在 IE<9 上确实受支持)。
Sorry, you can't find out what piece of code caused an event to be triggered, they're completely decoupled. You would have to have the triggering code co-operate by storing the values of its own
this
/event.target
in a variable for the triggered code to pick up later.But then if you have co-operation like that, you wouldn't need DOM Mutation Events.
If you have an event handling layer (as is part of many JS frameworks), you could put the
this
/target
tracking in that layer, so the triggered code could ask “what was the last event that fired, before me?”.But I'm not convinced this would be worth it. It's usually best to add your own co-operative hooks that communicate between components; you can't generally rely on DOM Mutation Events since they're not globally and completely supported (or indeed supported at all on IE<9).
又怎样呢
?
What about
?
有趣的。我看了这里(回答要格式化)
Interesting. I had a look here (answered to get formatting)