javascript - Polymer 纸张输入提交时如何调用函数?

标签 javascript html polymer

我有一个 polymer 应用程序,它接受文本输入 (ID) 并根据 ID 是否在列表中返回"is"或“否”。理想情况下,用户可以按 Enter 键或单击“查找”按钮,然后将调用“搜索 ID”功能。

我可以在不使用表单的情况下执行此操作吗? 如果我使用表单,我可以在不发出 post/put/get 请求的情况下执行此操作吗?数据全部存储在元素的属性(数组)中。

<dom-module id="demo-app">
  <template>
    <style>
      :host {
        display: block;
      }
    </style>
    <paper-card heading="Search for ID">
      <div class="card-content">
        <paper-input id="input" always-float-label label="ID"</paper-input>
      </div>
    </paper-card>
  </template>

  <script>
    Polymer({

      is: 'demo-app',

      properties: {
        myIds: {
          type: Array,
          value: ['testID1', 'testID2'],
        },
        inputObj: {
          type: Object,
          value: function(){
            return this.$.input;
          }
        },
        userInput: {
          type: String,
        },
      },
      onEnter: function(){
        if(this.myIds.includes(this.userInput)) {
          console.log(this.userInput);
        }
      },

    });
  </script>
</dom-module>

最佳答案

Polymer 的最佳实践是“使用平台”,在这种情况下,HTML(按钮的默认行为是提交其表单)和一些 JavaScript 就可以工作。

具体来说,将您的输入包装在表单中并添加一个按钮:

<form id="demoAppForm">
  <paper-card heading="Search for ID">
    <div class="card-content">
      <paper-input id="input" always-float-label label="ID"</paper-input>
    </div>
    <button>Lookup</button>
  </paper-card>
<form>

然后在提交表单时设置一个事件监听器,在该事件上设置 preventDefault (这样它就不会执行 GET 请求),并通过添加来对数据执行您想要的操作这些函数对您的 Polymer({...}) 调用:

attached: function() {
  this.listen(this.$.demoAppForm, 'submit', 'onSubmit');
},

onSubmit: function(event) {
  event.preventDefault();
  console.log('Lookup this:', this.$.input.value);
},

确保在分离元素时也删除事件监听器:

detached: function() {
  this.unlisten(this.$.demoAppForm, 'submit', 'onSubmit');
},

关于javascript - Polymer 纸张输入提交时如何调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946368/

相关文章:

javascript - 如何遍历对象数组并将每个对象显示在页面上? ( Vanilla JS)

javascript - 好的服务器 javascript 主机/框架?

javascript - 为什么我的下拉菜单在我的本地服务器上有效,但在我推送到 heroku 时却无效?

javascript - undefined 不是一个函数(评估'_this.props.navigation.navigate')

html - paper-tabs 标签边框 - polymer

html - 与其他方法相比,为什么 Polymer Project(Web Components)还没有出名?

javascript - 访问 Polymer 动态元素

javascript - ng-inspector 会减慢并导致页面崩溃。在哪里看

html - 如果我们将鼠标悬停在上面的图像上,下面的图像会隐藏

javascript - 按 'j' 时滚动到下一个 <div>