2016-11-08 84 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中引用聚合物的确切版本吗?我对此很新。谢谢... –