"jQuery方式"用HTML和文本混合替换仅文本节点? [英] "jQuery way" to replace just a text node with a mix of HTML and text?

查看:130
本文介绍了"jQuery方式"用HTML和文本混合替换仅文本节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Web浏览器用户脚本项目中,我只需要替换一个文本节点,而不会影响与该文本相同的父节点下的其他HTML元素.而且我需要用多个节点替换它:

In my web browser userscript project I need to replace just one text node without affecting the other HTML elements under the same parent node as the text. And I need to replace it with more than one node:

<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(我不想更改的新东西+之类的东西).另外请注意,我想保留初始空间,这似乎很棘手.

I know jQuery doesn't have a whole lot of support for text nodes. I know I could use direct DOM calls instead of jQuery. And I know I could just do something like $('#target').html(my new stuff + stuff I don't want to change). Also note that I'd like to preserve the initial space, this on its own seems to be tricky.

我想问的专家是,是否有最惯用的jQuery方式来做到这一点?

推荐答案

您基本上想用新内容替换第一个孩子(文本节点).您需要 http://api.jquery.com/replaceWith/

You basically want to replace the first child (text node) with the new content. You need 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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

<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;amp; <img src="/foobar.png"></div>

http://jsfiddle.net/NGYTB/1/

这篇关于"jQuery方式"用HTML和文本混合替换仅文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆