我无法通过 id 获取影子根中的元素。它将返回零。这是代码。它是用 clojurescript 编写的。
(p/defpolymer :query-component {:imports ["components/polymer/polymer.html"]
:style ".query-container
{margin: 20px;
display: inline-block;}"
:template [[:div.query-container
[:div
[:h4 {:style "display: inline-block;"} "Current Query"]
[:button {:style "float: right; margin-top: 10px;"
:on-click "{{runQuery}}"} "Run Query"]]
[:span "{{query.name}}"]
[:div#inputs]
;(cljs.reader/read-string "[:input.search-box {:type \"text\", :placeholder \"Country name\"}] ")
]]
:spec {:publish {:query {:value ""}}
:runQuery (fn []
(this-as this
(println (:query (js->clj (.-query this) :keywordize-keys true)))))
:queryChanged (fn []
(this-as this
(let [query (js->clj (.-query this) :keywordize-keys true)
inputs (:inputs query)]
)
(.log js/console (.getElementById js/document "#inputs"))
))}})
正如你所看到的,我试图通过 id“inputs”获取元素,但是它返回 null。 https://i.sstatic.net/GHMw7.png div 在那里,但我无法通过它的 id 获取它。这有什么原因吗?有没有办法通过它的 id 获取它?据我了解, get elementbyid 显然不会搜索影子根。
编辑: 我通过将影子根的名称作为元素的属性进行摆弄,找到了答案!
(p/defpolymer :query-component {:imports ["components/polymer/polymer.html"]
:style ".query-container
{margin: 20px;
display: inline-block;}"
:template [[:div.query-container
[:div
[:h4 {:style "display: inline-block;"} "Current Query"]
[:button {:style "float: right; margin-top: 10px;"
:on-click "{{runQuery}}"} "Run Query"]]
[:span "{{query.name}}"]
[:div#inputs]
;(cljs.reader/read-string "[:input.search-box {:type \"text\", :placeholder \"Country name\"}] ")
]]
:spec {:publish {:query {:value ""}}
:runQuery (fn []
(this-as this
(println (:query (js->clj (.-query this) :keywordize-keys true)))))
:queryChanged (fn []
(this-as this
(let [query (js->clj (.-query this) :keywordize-keys true)
inputs (:inputs query)
shadow-root (.-shadowRoot this)
input-div (.getElementById shadow-root "inputs")]
(set! (.-innerHTML input-div) "<span>Shadow DOM</span>"))))}})
这是工作代码。影子根是元素上的一个属性,名称为“shadowRoot”。
最佳答案
block 引用>It was my understanding that getElementById will search through the shadow roots but apparently not.
document
上没有任何查询方法将搜索阴影根,这是使它们阴影的部分原因。此规则的一个异常(exception)是如果您使用
querySelector[All]
以及专门刺穿影子根的选择器,即使用/deep/
或::shadow
)。
关于javascript - Polymer 通过 id 从影子根获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25043786/