检查多个DOM值

时间:2016-09-23 09:02:11

标签: jquery arrays

在jQuery中我有以下数组:

var arr = [{ "id" : "txt1", "value" : 180 }, { "id" : "txt2", "value" : "Text"}];

在keyup事件中,我希望这些文本字段中的任何一个都检查所有字段是否都具有数组中的相应值。

如何最有效地完成这项工作?

2 个答案:

答案 0 :(得分:0)

迭代数组并根据id。

绑定事件处理程序
// 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" />
&#13;
&#13;
&#13;

或者生成一个帮助对象,该对象将id作为属性名称和值作为其值。在click事件中,使用元素的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');
  }
})

&#13;
&#13;
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');
  }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt1" />
<input id="txt2" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以尝试这样的事情

var exist = false;
selectors = [];
$.each(arr,function(i,v) {
  selectors.push('#'+v.id);
});
selectors = selectors.join(',');
 $(selectors).keyup(function() {
     $.each(arr,function(i,v) {
       if($('#'+v.id).val() == v.value) { exist = true}
     });
     if(exist) {alert('at least one element has value from array')}
  });

&#13;
&#13;
var arr = [{
  "id": "txt1",
  "value": 180
}, {
  "id": "txt2",
  "value": "Text"
}];

var exist = false;
selectors = [];
$.each(arr, function(i, v) {
  selectors.push('#' + v.id);
});
selectors= selectors.join(',');

$(selectors).keyup(function() {
  console.log(selectors)
  $.each(arr, function(i, v) {
    if ($('#' + v.id).val() == v.value) {
      exist = true
    }
  });
  if (exist) {
    alert('at least one element has value from array')
  }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt1" />
<input id="txt2" />
&#13;
&#13;
&#13;