jQuery - 在 HTML 字符串的元素内插入文本 [英] jQuery - Insert text inside element of a HTML string

查看:36
本文介绍了jQuery - 在 HTML 字符串的元素内插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一个 html 字符串存储到 var HTML 中,我使用以下内容:

var HTML = $('.group').get(0).outerHTML;

使用console.log(HTML)的HTML输出为:

<div class="class1">数据123...

<div class="class2"><!--我想在这里插入文字-->

现在,我想在 div class="class2" 中插入一些文本.我正在使用以下代码:

$(HTML).find('.class2').text(你好!");

但是现在使用console.log(HTML) 的HTML 输出和以前一样旧的HTML.文本你好!"没有被插入.任何人都可以帮助解决这个问题.

完整代码如下:

<div class="class1">数据123...

<div class="class2">

<script type="text/javascript">var HTML = $('.group').get(0).outerHTML;$(HTML).find('.class2').text(你好!");控制台日志(HTML);

解决方案

您正在更新临时 DOM 元素,但这不会更改 HTML 字符串.您需要将 DOM 元素保存在一个变量中.

var new_div = $(HTML);new_div.find('.class2').text("你好!");console.log($(new_div).html());

I store an html string into var HTML, which I get using the following:

var HTML = $('.group').get(0).outerHTML;

The output of HTML using console.log(HTML) is:

<div class="group">
    <div class="class1">
        Data123...
    </div>
    <div class="class2">
        <!--I want to insert text here -->
    </div>
</div>

Now, I want to insert some text inside the div class="class2". I am using the following code:

$(HTML).find('.class2').text("Hello!");

But now the output of HTML using console.log(HTML) is the same old HTML as before. The text "Hello!" did not get inserted. Can anyone help with the solution.

Here is the complete code:

<div class="group">
    <div class="class1">
        Data123...
    </div>
    <div class="class2">
        
    </div>
</div>

<script type="text/javascript">
var HTML = $('.group').get(0).outerHTML;
$(HTML).find('.class2').text("Hello!");
console.log(HTML);
</script>

解决方案

You're updating a temporary DOM element, but that doesn't change the HTML string. You need to save the DOM elements in a variable.

var new_div = $(HTML);
new_div.find('.class2').text("Hello!");
console.log($(new_div).html());

这篇关于jQuery - 在 HTML 字符串的元素内插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆