Javascript 获取围绕特定标记的特定字符
我试过使用元素的Javascript 获取围绕特定标记的特定字符,javascript,html,dom,safari,iphone,Javascript,Html,Dom,Safari,Iphone,我试过使用元素的offsetParent属性,但是有很多可能性,比如div标签可能在粗体标签内,粗体标签可能在p标签内等等 我应该做什么来获取周围的文本?限制可能是10到20个字符 编辑: “环绕文本”的意思是->文本左侧10或20个字符,右侧10或20个字符。最简单的方法是,在每一侧用模糊字符串包装内部div的内容,然后在整个段落上使用正则表达式来查找添加的标记以及每一侧所需的字符数。大概是这样的: function myDivHTML(valueName){ if((obj = d
offsetParent
属性,但是有很多可能性,比如div标签可能在粗体标签内,粗体标签可能在p标签内等等
我应该做什么来获取周围的文本?限制可能是10到20个字符
编辑:
“环绕文本”的意思是->文本左侧10或20个字符,右侧10或20个字符。最简单的方法是,在每一侧用模糊字符串包装内部div的内容,然后在整个段落上使用正则表达式来查找添加的标记以及每一侧所需的字符数。大概是这样的:
function myDivHTML(valueName){
if((obj = document.getElementById(valueName)) && obj != null){
return obj.innerHTML;
}
}
您可能需要稍微调整正则表达式,使其匹配(例如)内部字符串前后的两个整词
示例@Tomalak-请检查示例并编辑到问题。是否可以在mobile Safari(iPhone)上运行此javascript?@sugar:没有理由它不应该在iPhone Safari上运行,但我会帮你检查。编辑工作很好。理论上,它应该在任何支持Javascript和innerText/textContent.OK的现代浏览器中工作!让我试试这个。
function myDivHTML(valueName){
if((obj = document.getElementById(valueName)) && obj != null){
return obj.innerHTML;
}
}
var full, result,
// textContent for w3 compliance, innerText for IE
txt = "textContent" in document.body ? "textContent" : "innerText",
// Get references to both divs and store the current text of `xyz`
out = document.getElementById("outer"),
xyz = document.getElementById("xyz"),
old = xyz[txt];
// wrap the inner text with something we can easily search for:
xyz[txt] = "||||" + xyz[txt] + "||||";
// Get the whole text, change the DOM text back to what it was
full = out[txt];
xyz[txt] = old;
// Find the text with our markers and surrounding text:
result = /.{0,10}\|{4}.*?\|{4}.{0,10}/.exec(full);
alert(result[0]);
// -> "ch button ||||will highlight all|||| the words"
// Finally, replace your wrapping strings:
result = result[0].replace(/\|{4}/g, "");
alert(result);
// -> "ch button will highlight all the words"