在 jQuery 中,我有以下数组:
var arr = [{ "id" : "txt1", "value" : 180 }, { "id" : "txt2", "value" : "Text"}];
在 keyup 事件中,我希望这些文本字段中的任何一个都检查所有字段是否具有数组中的相应值。
我怎样才能最有效地做到这一点?
最佳答案
迭代数组并根据 id 绑定(bind)事件处理程序。
// iterate over the array elements
arr.forEach(function(v) {
// get element using the id selector and then bind
// keyup event for listening
$('#' + v.id).keyup(function() {
// compare the current value with array element value
if (this.value == v.value) {
// do the rest of code
}
})
})
var arr = [{
"id": "txt1",
"value": 180
}, {
"id": "txt2",
"value": "Text"
}];
arr.forEach(function(v) {
$('#' + v.id).keyup(function() {
if (this.value == v.value) {
console.log('matched');
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt1" />
<input id="txt2" />
或者生成一个辅助对象,其中包含 id 作为属性名称和 value 作为其值。在单击事件时,使用元素的 id 属性从数组中获取值。
// object for holding corresponding value based on id
var obj = {},
// variable for selector
sel;
// iterate and generate object and selector
sel = arr.map(function(v) {
// add object property
obj[v.id] = v.value;
// return id selector
return '#' + v.id;
// combine the id selectors
}).join();
// bind keyup event
$(sel).keyup(function() {
// compare the current value and correponding array object value
if (this.value = obj[this.id]) {
console.log('matched');
}
})
var arr = [{
"id": "txt1",
"value": 180
}, {
"id": "txt2",
"value": "Text"
}],
obj = {},
sel;
sel = arr.map(function(v) {
obj[v.id] = v.value;
return '#' + v.id;
}).join();
$(sel).keyup(function() {
if (this.value == obj[this.id]) {
console.log('matched');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt1" />
<input id="txt2" />
关于jquery - 检查多个 DOM 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39656802/