为何Polymer的iron-selector组件无法正常工作?
嘿,我帮你排查下这个问题,先看代码里最显眼的错误,再给你补充几个关键检查点:
1. 标签闭合错误(核心问题)
你所有的<div>标签都错误地用了</a>来闭合,这会导致浏览器DOM解析混乱,元素结构异常,自然没法触发点击交互。把每个</a>改成</div>就好,修正后的代码片段:
<iron-selector selected='{{choice}}' attr-for-selected='option'> <div option='home'>Homepage</div> <div option='list'>List</div> <div option='delete'>Delete items</div> </iron-selector> <h1>Your choice: {{choice}}</h1>
2. 额外验证点
如果修正标签后还是没反应,再检查这两个地方:
- 组件是否正确引入:确保页面头部已经导入了
iron-selector组件。如果是Polymer 2.x及以下版本,需要添加:
要是用的Polymer 3+,则用ES模块导入:<link rel="import" href="/bower_components/iron-selector/iron-selector.html">import '@polymer/iron-selector/iron-selector.js'; - 数据绑定是否在Polymer环境中运行:
{{choice}}这种绑定语法只有在Polymer自定义元素的模板内才会生效。如果是直接在普通HTML页面里写这段代码,双向绑定不会工作,你需要把代码封装到自定义元素中,比如这样的完整示例:
之后在页面中使用<link rel="import" href="/bower_components/polymer/polymer-element.html"> <link rel="import" href="/bower_components/iron-selector/iron-selector.html"> <dom-module id="my-page-switcher"> <template> <iron-selector selected='{{choice}}' attr-for-selected='option'> <div option='home'>Homepage</div> <div option='list'>List</div> <div option='delete'>Delete items</div> </iron-selector> <h1>Your choice: {{choice}}</h1> </template> <script> class MyPageSwitcher extends Polymer.Element { static get is() { return 'my-page-switcher'; } static get properties() { return { choice: { type: String, value: 'home' // 设置默认选中项 } }; } } customElements.define(MyPageSwitcher.is, MyPageSwitcher); </script> </dom-module><my-page-switcher></my-page-switcher>就能正常工作了。
内容的提问来源于stack exchange,提问作者TJRC
相关产品推荐
相关产品推荐

