【问题标题】:Polymer 1.0 Local Dom issue with this.$ selectorPolymer 1.0 本地 Dom 问题与 this.$ 选择器
【发布时间】:2015-08-20 01:57:36
【问题描述】:

我知道我们可以使用 this.$ 选择器从本地 dom 中选择元素。但是,如果我有一个在单击按钮时触发的函数,我将如何在此函数中通过 ID 访问元素?

例如:

HTML:

 <input id = "counter" value = "10">

JavaScript:

var testButton = this.$.testButton;
$(testButton).click(function(){
   var counter = this.$.counter;
   console.log(counter.value);
}

问题是“this.$.counter”现在引用了按钮

【问题讨论】:

    标签: javascript polymer this shadow-dom


    【解决方案1】:

    问题在于,当您使用 Polymer 时,它不会改变事件处理程序和 this 的工作方式。事件处理程序中的this 对应于testButton,因为它是触发click 事件的元素,而不是Polymer 元素。

    试试这个:

    var testButton = this.$.testButton;
    var counter = this.$.counter;
    $(testButton).click(function(){
       console.log(counter.value);
    }
    

    【讨论】:

    • 啊当然。漫长的一天工作完全只是大脑在那里放屁。非常感谢!
    【解决方案2】:

    使用 Polymer 的 onTap 函数代替 onClick 也可以解决此问题。

    【讨论】:

      【解决方案3】:

      如果您将 jQuery 与聚合物一起使用,则很有可能您做错了什么。

      <button on-tap='foo'>
      

      ...

      Polymer({ 
      

      ...

        foo: function(event){
          console.log(this.$.counter);
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多