jQuery用字符串替换span内容

时间:2017-10-30 11:25:45

标签: jquery typescript

我有一个包含html标记的字符串,格式如下:

<p>
  <span class="xyz-display">
    <lots of other contents>
  </span>
</p>

在对字符串运行卫生之前,我需要用字符串替换<span class="xyz-display">内的所有内容。所以看起来如下:

<p>
  <span class="xyz-display">
    abc
  </span>
</p>

在此之后,我需要将abc替换为原始内容<lots of other contents>。如何使用jQuery实现这一目标?

谢谢和问候

4 个答案:

答案 0 :(得分:0)

尝试此操作以更改<span>标记的内容:

$("span.xyz.display").html("<lots of other contents>")

答案 1 :(得分:0)

你可以使用

{{1}}

答案 2 :(得分:0)

我添加了一个带按钮的演示。这里的主要概念是

$(".xyz-class > span").html(what_to_add);

它实际上做的是采用xyz-class的实例。进一步&#34;&gt;&#34;表示子元素,它是span元素,html(what_to_add)用于将HTML代码应用于该部分。

这是一个代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello world</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        function add(){
            var what_to_add = '<p>Enter name </p> <input type="text" /> ';
            $(".xyz-class > span").html(what_to_add);
        }
    </script>
</head>
<body>
    <div>
        <p class="xyz-class">
            <span>Hello world</span>
        </p>
        <button onclick="add()">Add</button>
    </div>
</body>
</html>

要添加字符串,您可以将what_to_add分配给您需要的某个字符串。即what_to_add =&#34;你的字符串。&#34; 希望它会对你有所帮助。

答案 3 :(得分:0)

$(function(){
  $('.xyz-display').html('Hello! ')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="xyz-display">
  abc
</span>

尝试这个。

相关问题