我有一组输入字段,每个字段都有“smarty_address_check”类
<input type="text" class="smarty_address_check" value="this is a new value" />
<input type="text" class="smarty_address_check" value="this value has been unchanged" />
etc
我需要做的是
数组中的值是输入字段的原始默认值/示例值,如果用户没有更改它们,我想对此进行操作。
var exampleAddressPresent = false;
for (var i = 0; i<smarty_address_check.length; i++) {
$('.smarty_address_check').each(function() { //For each of inputs
if (smarty_address_check[i].match($(this).val())) { //if match against array
var exampleAddressPresent = true; //Example address present
console.log($(this).attr("id")); //store id of unchanged input
}
});
}
我觉得这是错误的编程逻辑,更不用说我无法解决为什么它不能正常工作。我基本上想做的就是比较一个字符串与另一个字符串。有人知道更好的方法吗?
答案 0 :(得分:3)
您不需要match()
来比较两个字符串。有共同的===
比较运算符
if(smarty_address_check[i] === $(this).val()) {
编辑:如果数组的索引与输入的索引/位置匹配,则可以通过使用相同的索引来避免外部循环
$('.smarty_address_check').each(function(index) { //For each of inputs
if (smarty_address_check[index] === $(this).val()) { //if match against array
exampleAddressPresent = true; //Example address present
console.log($(this).attr("id")); //store id of unchanged input
}
});
答案 1 :(得分:0)
如果您要检查的array
是an Array of strings
,可能的解决方案是:
var myArray = ['apples', 'mangoes', 'bananas'] // example Array of strings
var string = myArray.join(':'); // we'll get "apples:mangoes:bananas"
var myValue = 'apples' // example input value
if(string.indexOf(myValue) !== -1)
// do something (i.e. myValue matches with one of the values on myArray)
祝你好运