【问题标题】:Polymer web component content click event not firingPolymer Web 组件内容单击事件未触发
【发布时间】:2014-08-23 20:26:08
【问题描述】:

我刚刚创建了我的第一个元素作为测试,但我遇到了点击事件的问题。我的元素只是一个带有单击事件的按钮,用于增加一个计数器,该计数器显示为按钮文本的一部分。我还添加了一个内容标签,以便您可以向按钮添加其他文本。

当我点击 Chrome 中的按钮时,如果我点击内容文本,则不会触发 click 事件。我必须实际单击按钮元素/按钮中的计数才能触发事件。尽管在 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

【问题讨论】:

    标签: javascript polymer web-component dom-events shadow-dom


    【解决方案1】:

    如果您将额外的文本包装在 span 中,它会起作用。

    <my-counter><span>Times a Day</span></my-counter>
    

    看到这个JSbin

    我想这与textNodesdon't 触发大多数事件的事实有关(请参阅here)。 如果您将LightDOMShadowDOM 与事件混合使用,请务必阅读此article 和此SO thread

    您的代码在 Chrome 与其他浏览器中的行为不同的原因是 Chrome 目前是唯一一个提供本机 shadow dom 实现的浏览器。 Firefox 将在几周内发货。更多最新信息在这里:caniuseit - shadowdom

    【讨论】:

    • 太棒了!谢谢大家,这真的很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多