代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
p{
border:10px solid #ccc;
background:#FFC;
width:400px;
padding:20px;
font-size:16px;
font-family:微软雅黑;
}
span1{
background-color:#FF0000;
}
</style>
</head>
<body>
<input type="text"/>
<input type="button" value="查找">
<input type="text"/>
<input type="button" value="替换">
<p>当js文件放在head里面时,如果绑定了onclick事件,就会出现这样的错误,是因为W3School的写法是浏览器先加载完按钮节点才执行的js,所以当浏览器自顶向下解析时,找不到onclick绑定的按钮节点,于是报错。因此,需要把js文件放在底部加载,就会避免该问题。</p>
</body>
<script>
var aInp=document.getElementsByTagName('input');
var oP=document.getElementsByTagName('p')[0];
aInp[1].onclick=function(){
var str=aInp[0].value;
if(!str)return;
var aSch=oP.innerHTML.split(str);
if (aSch.length>1){
oP.innerHTML=aSch.join('<span1>'+str+'</span1>');
}else{
alert("没有你要查找的内容");
}
};
aInp[3].onclick=function(){
var str=aInp[0].value;
var newstr=aInp[2].value;
if(!str)return;
var aSch=oP.innerHTML.split(str);
if(aSch.length>1){
oP.innerHTML=aSch.join('<span>'+newstr+'</span>')
}else{
alert("没有你要替换的内容");
}
}
</script>
</html>
效果图
原文
查找
替换