我刚刚创建了第一个元素作为测试,但遇到了单击事件的问题。我的元素只是一个带有单击事件的按钮,用于增加计数器,该计数器显示为按钮文本的一部分。我还添加了一个内容标签,以便您可以向按钮添加其他文本。
当我点击 Chrome 中的按钮时,如果我点击内容文本,则不会触发点击事件。我必须实际单击按钮元素/按钮中的计数才能触发事件。尽管在 Firefox、Safari 和 Opera 中一切似乎都工作正常。我可以单击这些浏览器中按钮上的任意位置,然后单击事件将会触发。难道我做错了什么?这只是 Chrome 的一个错误吗?这是我的代码:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Test Element</title>
<script src="bower_components/platform/platform.js"></script>
<link rel="import" href="elements/my-counter.html">
</head>
<body unresolved touch-action="auto">
<my-counter count=5>Times a Day</my-counter>
</body>
</html>
elements/my-counter.html
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="my-counter" attributes="count">
<template>
<button on-click="{{increment}}">{{ count }} <content></content></button>
</template>
<script>
Polymer('my-counter', {
count: 0,
increment: function(event, detail, sender) {
console.log(event, detail, sender);
++this.count;
}
});
</script>
</polymer-element>
如果您想下载并自行测试,此代码也在 GitHub 上:https://github.com/andersryanc/playing-with-polymer/tree/master/my-counter
最佳答案
如果您将多余的文本包装在 span
中,它就可以工作。
<my-counter><span>Times a Day</span></my-counter>
查看此JSbin 。
我猜这与 textNodes
不会触发大多数事件有关(请参阅 here )。
如果您将 LightDOM
和 ShadowDOM
与事件混合使用,请务必阅读本文 article还有这个SO thread .
您的代码在 Chrome 与其他浏览器中的行为不同的原因是 Chrome 是目前唯一提供 native Shadow dom 实现的浏览器。 Firefox 将在几周内发布。更多最新信息请点击:caniuseit - shadowdom
关于javascript - polymer 网络组件内容点击事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24541404/