2016-11-08 38 views
0

Here is my JSBin聚合物1.x:訪問DOM中的元素 - 如果

點擊「名字:詹姆斯」文本。

我在dom-if中有一個輸入元素。在一個事件中,我讓dom如果通過,所以元素將會存在,但在dom-if條件通過後我不能立即訪問輸入元素。

可能我需要知道何時實際評估了dom-if,以及爲什麼即使條件成爲true,元素也不存在。

<!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"> 
    <link href="paper-input/paper-input.html" rel="import"> 
</head> 
<body> 

<dom-module id="x-element"> 

<template> 
    <style></style> 
    <template is="dom-if" if="{{!editMode}}"> 
    <span id="name" on-tap="_makeEditable">{{name}}: {{value}}</div> 
    </template> 
    <template is="dom-if" if="{{editMode}}"> 
    <paper-input id="input" label="{{name}}" value="{{value}}"></paper-input> 
    </template> 

</template> 

<script> 
    (function(){ 
    Polymer({ 
     is: "x-element", 
     properties: { 
     editMode: { 
      type: Boolean, 
      value: false 
     }, 
     name: { 
      type:String, 
      value:"First Name" 
     }, 
     value: { 
      type:String, 
      value:"James" 
     } 
     }, 
     _makeEditable: function() { 
     this.editMode = true; 
     //how to find the input element here 
     //this.$$('#input').querySelector("input").focus(); 
     //this.$.input.querySelector("input").focus(); 
     } 
    }); 
    })(); 
</script> 

</dom-module> 

<x-element></x-element> 

</body> 

回答

1

這是因爲設置this.editModetrue並不是實時更新的DOM。

你應該異步運行你的選擇,使聚合物具有一定的時間來更新DOM,如:

this.async(function() { 
    this.$$('#input').focus(); 
}) 

小提琴here

+0

謝謝@Yurii!這工作。
儘管我面臨着另一個問題,但是'。($#input')。focus()'對我來說不起作用。它在我做這個。$$('#input')。querySelector('input')。focus()'時起作用。它在JSBin中運行良好,這是我實際做的更簡單的版本。任何提示,我應該看看這個? –

+0

你可以發佈小提琴嗎? –

+0

正如我所說的,@Yurii,它在JSBin中工作正常,只在我的本地機器中出現問題。可能是我使用的聚合物版本(v1.6)中的一個錯誤!?你知道我可以如何在JSBin中引用聚合物的確切版本嗎?我對此很新。謝謝... –