我有一段代码可以在表格中搜索某个短语。一旦找到该短语,它就会将当前单元格的innerHTML 返回到页面顶部附近的div。
我遇到的问题是这样的:
除非要搜索的短语包含任何特殊字符(括号和与号等),否则代码可以完美运行。我尝试修改“Western & Central"
to "Western & Central"
但不幸的是,代码仍然无法找到该短语。
代码如下:
// Function for searching tables for specific map/device combination.
function findMap(map, device)
{
var flag = false; // to check if the map has been found yet
// Add <strong> tags to map string so it is easier to search for
var mapstring = "<strong>" + map;
var map_regex = new RegExp( mapstring,'i');
// create array of tables
var tables = document.getElementsByTagName('table');
for (var t = 2; t < tables.length; t++)
{
// create array of rows
var tablerows = tables[t].rows;
for (var r = 2; r < tablerows.length; r++)
{
currentRow = tablerows[r];
// Check if current row contains map name
if (currentRow.innerHTML.match(map_regex))
{
var tablecells = currentRow.cells;
for (var c = 1; c < tablecells.length; c++)
{
currentCell = tablecells[c];
// Check if current cell contains device name
if (currentCell.innerHTML.match(device))
{
document.getElementById("boxy2").innerHTML = currentCell.innerHTML;
flag = true;
}
if (flag == true) return;
}
if (flag == true) return;
// search for x20 if 920 was not found etc
if (device == "910")
device = "x10";
else if (device == "920")
device = "x20";
else if (device == "930")
device = "x30";
else if (device == "940")
device = "x40";
else if (device == "950")
device = "x50";
// search cells again
for (var c = 1; c < tablecells.length; c++)
{
currentCell = tablecells[c];
if (currentCell.innerHTML.match(device))
{
document.getElementById("boxy2").innerHTML = currentCell.innerHTML;
flag = true;
}
if (flag == true) return;
}
if (flag == true) return;
}
if (flag == true) return; else { document.getElementById("boxy2").innerHTML="Map not available on this device."; }
}
}
}
任何有关此事的帮助将不胜感激!
由于您只是想检查特定字符串是否存在,我认为如果您使用,您的解决方案可能会更强大indexOf http://www.w3schools.com/jsref/jsref_IndexOf.asp而不是正则表达式。
使用正则表达式,如果您正在寻找特殊字符,例如[
or ]
or (
or )
那么你需要逃避它们,这只是我认为你不需要引入的另一层复杂性。
因此,请尝试替换正则表达式用法,例如......
if (currentRow.innerHTML.match(map_regex))
有了这个...
if (currentRow.innerHTML.indexOf(mapString)!=-1)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)