道歉,因为这是线程的转发,我无法再访问或评论。Javascript搜索子字符串
我正在尝试编写一个javascript函数,该函数将在html页面中搜索包含在我的搜索栏中的子字符串的所有指定div。我该如何做到这一点?
这是我的代码到目前为止,我有它的工作,所以showMe
方法将只显示选定的div,我只需要子字符串代码现在工作。有人可以帮忙吗?
<html>
<head>
<script type="text/javascript">
function dynamicSearch() {
var val = document.getElementById('search').value;
if (val == '')
val = '-1';
var srch = new RegExp(val, "gi");
var els = document.getElementsByClassName('row');
for (var idx in els) {
if (idx != parseInt(idx))
continue;
var el = els[idx];
if (typeof(el.innerHTML) !== 'undefined') {
console.log(el.innerHTML);
if (srch.test(el.innerHTML)) {
el.style.display = 'block';
} else {
el.style.display = 'none';
}
}
}
}
function showMe (it, box) {
var vis = (box.checked) ? "block" : "none";
document.getElementById(it).style.display = vis;
}
</script>
</head>
<body>
<form>
<label for="search">Search:</label>
<input type="text" name="search" id="search" onkeyup="dynamicSearch()"/>
<input type="checkbox" name="modtype" value="value1" onclick="showMe('div1', this)" />value1
<input type="checkbox" name="modtype" value="value2" onclick="showMe('div2', this)" />value2
<input type="checkbox" name="modtype" value="value3" onclick="showMe('div3', this)" />value3
<input type="checkbox" name="modtype" value="value4" onclick="showMe('div4', this)" />value4
<input type="checkbox" name="modtype" value="value5" onclick="showMe('div5', this)" />value5
<div class="row" id="div1" style="display:none">Show Div 1</div>
<div class="row" id="div2" style="display:none">Show Div 2</div>
<div class="row" id="div3" style="display:none">Show Div 3</div>
<div class="row" id="div4" style="display:none">Show Div 4</div>
<div class="row" id="div5" style="display:none">Show Div 5</div>
</form>
</body>
</html>
我这里的代码可以正常运行了我的复选框,但我不能让它只显示搜索到的字符串作为结果(即DynamicSearch功能不起作用,但SHOWME一个呢?或者至少我不能让DynamicSearch代码工作?)
除非你有特殊原因的空隙,避免它,请*请*考虑的jQuery或其他一些库DOM遍历/操控。此外,需要将脚本封装在HTML注释标记中('')已经过去了,您不应该再这么做了,而且您尤其不应该忽略开头的''<! - ''标记,这是一个JavaScript解析错误。 – meagar 2011-04-28 20:20:30
我打开使用JQuery,我只是无法让函数正常工作(请参阅下面的答案我的评论)。我想我已经解决了你现在发布的其他问题。非常感谢回复。 – user729051 2011-04-28 20:48:23