我一直在研究测试数组中是否存在值,并继续获取indexOf('textvalue')的匹配项。
但是,我的'textvalue'将是一个子字符串,因此不会匹配。这是因为我将字段名称传递给方法,只需要删除“门:左前方”;通过匹配“门”上的数组项来显示文本。有谁知道我怎么能做到这一点?
以下是我正在处理的示例代码:
(spnSelectedDisclosures将有一个选定字段的列表,这是从文本中删除前一个字段选择的代码,它是以分号分隔的。)
var currentText = $("#spnSelectedDisclosures").text();
var existingArr = currentText.split(";")
for (i=0;i < existingArr.length;i++) {
var indexItem = " " + existingArr[i].toString(); // why is this still an object, instead of a string? Adding a space to it was a desperate try to make indexItem a string variable.
if (indexItem.contains(substringText)) { // offending line, saying the object has no method 'contains'
alert("there's been a match at: " + i);
textToRemoveIndex = i;
break;
}
}
var textToRemove = existingArr[textToRemoveIndex];
var newText = currentText.replace(textToRemove,"");
$("#spnSelectedDisclosures").text(newText);
答案 0 :(得分:3)
这是什么?
for (i=0;i < existingArr.length;i++) {
if (existingArr[i].indexOf(substringText) > -1) {
alert("there's been a match at: " + i);
textToRemoveIndex = i;
break;
}
}
答案 1 :(得分:0)
String.contains()的支持非常有限:
浏览器兼容性
Chrome Not supported Firefox (Gecko) 19.0 (19) Internet Explorer Not supported Opera Not supported Safari Not supported
您需要使用正则表达式或indexOf。
if (indexItem.indexOf(substringText)!==-1) {