在我的 Web 浏览器用户脚本项目中,我只需要替换一个文本节点,而不影响与文本位于同一父节点下的其他 HTML 元素。我需要用多个节点替换它:
<div id="target"> foo / bar; baz<img src="/image.png"></div>
需要成为:
<div id="target"> <a href="#">foo</a> / <a href="#">bar</a>; <a href="#">baz</a><img src="/image.png"></div>
我知道 jQuery 对文本节点没有太多支持。我知道我可以使用直接 DOM 调用而不是 jQuery。我知道我可以做类似的事情$('#target').html(
我的新东西+
我不想改变的东西)
。另请注意,我想保留初始空间,这本身似乎很棘手。
我想请教这里的专家的是,有没有最惯用的 jQuery 方法来做到这一点?
您基本上想用新内容替换第一个子节点(文本节点)。你需要http://api.jquery.com/replaceWith/ http://api.jquery.com/replaceWith/
// Text node we want to process and remove
var textNode = $("#target").contents().first();
// Break the text node up
var parts = textNode.text().split(/\s/);
// Put links around them
var replaceWith = "";
for (var i =0; i < parts.length;i++) {
replaceWith += "<a href='http://www.google.com'>" + escapeHTML(parts[i]) + "</a> ";
}
// Replace the text node with the HTML we created
textNode.replaceWith(replaceWith);
function escapeHTML(string) {
return string.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="target">example, handles escaping properly, you should see an ampersand followed by "amp;" here: &amp; <img src="/foobar.png"></div>
http://jsfiddle.net/NGYTB/1/ http://jsfiddle.net/NGYTB/1/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)