簡體   English   中英

Polymer 1.x:強制訪問dom-if模板中的DOM節點

[英]Polymer 1.x: Imperatively accessing DOM nodes inside a dom-if template

這是我的jsBin

我想通過其id訪問dom-if模板中的DOM節點。 使用我現有的代碼,我希望在嘗試將這些節點轉換為布爾true時會看到true ,但是我會得到false (即undefined )。

重新創建問題的步驟:

  1. 打開此jsBin
  2. 通過顯示FooBar而不顯示Baz了解右側的HTML窗格是否正常工作。
  3. 觀察控制台,了解id="foo"節點是可訪問的,但id="bar"id="baz"元素不可訪問。 這是我的問題。

如何強制訪問那些節點?

http://jsbin.com/kemoravote/1/edit?html,控制台,輸出
 <!doctype html> <head> <meta charset="utf-8"> <base href="https://polygit.org/components/"> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link href="polymer/polymer.html" rel="import"> <link href="iron-form/iron-form.html" rel="import"> </head> <body> <dom-module id="x-element"> <template> <style></style> <div id="foo">Foo</div> <template is="dom-if" if="{{show}}"> <div id="bar">Bar</div> </template> <template is="dom-if" if="{{!show}}"> <div id="baz">Baz</div> </template> </template> <script> (function(){ Polymer({ is: "x-element", properties: { show: { type: Boolean, value: function() { return true; } } }, attached: function() { console.log('foo', !!this.$.foo); console.log('bar', !!this.$.bar); console.log('baz', !!this.$.baz); }, }); })(); </script> </dom-module> <x-element></x-element> </body> 

$選擇器不起作用。 您必須按如下方式使用$$

console.log('baz', !!this.$$('#baz'));

這是jsBin

http://jsbin.com/xogediyato/1/edit?html,控制台,輸出

 <!doctype html> <head> <meta charset="utf-8"> <base href="https://polygit.org/components/"> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link href="polymer/polymer.html" rel="import"> <link href="iron-form/iron-form.html" rel="import"> </head> <body> <dom-module id="x-element"> <template> <style></style> <div id="foo">Foo</div> <template is="dom-if" if="{{show}}"> <div id="bar">Bar</div> </template> <template is="dom-if" if="{{!show}}"> <div id="baz">Baz</div> </template> </template> <script> (function(){ Polymer({ is: "x-element", properties: { show: { type: Boolean, value: function() { return true; } } }, attached: function() { console.log('foo', !!this.$.foo); console.log('bar', !!this.$.bar); console.log('baz', !!this.$.baz); console.log('bar', !!this.$$('#bar')); console.log('baz', !!this.$$('#baz')); }, }); })(); </script> </dom-module> <x-element></x-element> </body> 

使用

[英]Using <template is=“dom-if” with a condition

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM