jquery - 检查多个 DOM 值

标签 jquery arrays

在 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/

相关文章:

JQuery 获取文本连接名称

jquery-animate - 可以使 jquery.live() 与负载一起工作吗?

php - 数组验证

jquery - 如何使用数组索引对无序列表进行排序

java - java中合并两个已排序的数组

javascript - 如何使用jquery改变图像的颜色

php - 移动到另一页时发出警报

javascript - 按列 Javascript/CSS 在页面中组织生成的标签

java - 如何在不指向 Java 源列表中的对象的情况下复制 ArrayList?

php - 在多维数组中查找重复值