87,910
社区成员
发帖
与我相关
我的任务
分享
<div id="box">谁吃饭?<p>你吃饭了吗<a href="xx.html" title="吃饭">你吃饭吗</a>呵呵吃饭吧<img src="xx.jpg" alt="吃饭吧" title="谁吃饭" />呵呵</p>吃饭了吗
<div>谁吃饭?<p>你吃饭了吗<a href="xx.html" title="吃饭">你<span>跟谁吃饭</span>吗</a>呵呵吃饭吧<img src="xx.jpg" alt="吃饭吧" title="谁吃饭" />呵呵</p>吃饭了吗</div>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="box">
干嘛去了,吃饭去了吗?
<p>hehe,shid吃饭去了</p>
<img src="images.jpg" alt="hehe吃饭了">
爱干嘛干嘛吃饭还不给?
</div>
<script>
var oBox = document.getElementById("box");
var oBox2 = document.getElementById("box2");
for(var i=0; i<oBox.childNodes.length;i++){
if(oBox.childNodes[i].nodeType==3){
str = oBox.childNodes[i].nodeValue.replace(/(吃饭)/g,function($1){
return '<span style="position:relative;text-decoration:underline;"><a href="#" target="_blank">' + $1 + '</a></span>';
})
oBox.childNodes[i].nodeValue = str;
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="box">
干嘛去了,吃饭去了吗?
<p>hehe,shid吃饭去了</p>
<p>hehe,,<a href="#">shid吃饭去</a>了</p>
<img src="images.jpg" alt="hehe吃饭了">
爱干嘛干嘛吃饭还不给?
</div>
<div id="box2">吃饭gogo</div>
<script>
if (typeof Element != 'undefined' && !Element.prototype.contains) Element.prototype.contains = function (o) { do { if (this == o) return true } while (o = o.parentNode); return false };
function parentIsA(o) { do { if (o.tagName == 'A') return true } while (o = o.parentNode); return false; }
var oBox = document.getElementById("box"), key = '吃饭';
var range;
if (document.createRange) range = document.createRange();
else range = document.body.createTextRange();
if (range.findText) {//ie
while (range.findText(key)) {
if (!parentIsA(range.parentElement())&&oBox.contains(range.parentElement())) range.pasteHTML('<span style="position:relative;text-decoration:underline;"><a href="#" target="_blank">' + key + '</a></span>');
else range.move('character', key.length)
}
} else if (window.find) {
var s, n;
s = window.getSelection();
while (window.find(key)) {
if (!parentIsA(s.focusNode) && oBox.contains(s.focusNode)) {
var n = document.createElement("span");
n.style.position = "relative"
n.style.textDecoration = "underline"
s.getRangeAt(0).surroundContents(n);
n.innerHTML = '<a href="#" target="_blank">' + key + '</a>';
}
}
s.removeAllRanges();
}
</script>
</body>
</html>