Axe*_*eem 2 html javascript highlight
我做了一个代码,应该突出搜索字符串,但它不起作用.
这是代码:
<body>
<div>div is here</div>
<div id="divid">
<div>this is a div 1</div>
<div> this is a div 2</div>
<div> this is a div3</div>
</div>
<div> another div is here</div>
</body>
Run Code Online (Sandbox Code Playgroud)
这是一个javascript代码.
function checkit(){
var hlWord = "div";
var nregex = new RegExp(hlWord,"gi");
var div = document.getElementById("divid").getElementsByTagName('div');
for(var i=0; i <= div.length; i++){
var div1 = div[i].innerHTML;
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>");
div1.innerHTML = rword;
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码中存在更多错误.让我纠正一下:
function checkit(){
var hlWord = "div"; //Define string that will be emphasized by <b> tag
var nregex = new RegExp(hlWord,"gi");//Create global, case-insensitive regexp
var div = document.getElementById("divid").getElementsByTagName('div'); //Get element collection of divs in div#divid
for(var i=0; i < div.length; i++){ //Loop through my element collection
var div1 = div[i].innerHTML; //Get the innerHTML of on of the divs
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>"); //Surround my string with <b>
div[i].innerHTML = rword; //Change the innerHTML back
}
}
Run Code Online (Sandbox Code Playgroud)
你用过这个for条件:i<=div.length.这是错的.不要忘记,我们从0算起来:[0, 1, 2, 3].length = 4.此类数组的最后一个元素具有索引3.这[]是一个数组文字.
错误地,你分配了div1.innerHTML.div1是一个字符串.您要更改的元素是div[i].
| 归档时间: |
|
| 查看次数: |
1485 次 |
| 最近记录: |