简体   繁体   English

聚合物1.x:dom-if中的访问元素

[英]Polymer 1.x: accessing element within dom-if

Here is my JSBin 这是我的JSBin

Click on the "First Name: James" text. 单击“名字:James”文本。

I have an input element within dom-if. 我在dom-if中有一个输入元素。 In an event, I am making dom-if to pass and so the element will come into existence but I cannot access the input element immediately after making the dom-if condition pass. 在某种情况下,我正在使dom-if通过,因此该元素将存在,但是在使dom-if条件通过后,我无法立即访问输入元素。

May be I need to know when the dom-if is actually evaluated and why the element does not exist even if the condition has become true. 可能是我需要知道dom-if的实际计算时间,以及即使条件变为真也为什么不存在该元素的原因。

<!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>

This is because setting this.editMode to true does not update the DOM instantaneously. 这是因为将this.editMode设置为true不会立即更新DOM。

You should be running your selector asynchronously, so that Polymer has some time to update the DOM, such as: 您应该异步地运行选择器,以便Polymer有一些时间来更新DOM,例如:

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

Fiddle here . 在这里摆弄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM