我有一个 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/