我想知道如何从父元素捕获子元素发生的事件,如下所示。我知道此方法可以使用 this
捕获事件,但我需要从子元素中获取它。
我不想从li
捕获事件并通过全局变量或其他类似方式将信息传输到foo
,因为我最终将实现一个mousemove
事件,每次触发都会发送鼠标的位置,通过全局变量技术发送该事件的效率非常低(如 API here 中所示),并且会减慢应用程序的速度。
<polymer-element name="foo">
<template>
<ul>
<li>This is my child element</li>
</ul>
</template>
<script>
Polymer('foo', {
ready: function() {
document.querySelector('li').addEventListener('mousedown', function() {
console.log('mousedown event working');
})
}
});
</script>
</polymer-element>
预先感谢您提供的任何见解。
最佳答案
不要使用 document.querySelector()
因为您的 li
元素位于 shadow dom 内 polymer 元素。顺便提一句。元素名称不正确,it must contain a dash .
您可以使用automatic node finding Polymer 的功能来获取 li 元素。为元素分配一个 id 并使用 this.$
属性(或者,如果您不想分配 id,可以使用 this.shadowRoot.querySelector()
):
<li id="item">This is my child element</li>
this.$.item.addEventListener(...);
但使用 Polymer,您可以 declaratively assign the callback function到 li
元素,这会产生更具可读性的代码:
<polymer-element name="my-foo">
<template>
<ul>
<li on-mousedown="{{mousedown}}">This is my child element</li>
</ul>
</template>
<script>
Polymer('my-foo', {
mousedown: function() {
console.log('mousedown event working');
}
});
</script>
</polymer-element>
关于Polymer:从父元素捕获子元素的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26157980/