javascript - 更改段落 jQuery 中的内部值

标签 javascript jquery html css ajax

我想更改段落中的两个值,评论和源文本,但我的 jQuery 似乎只更改评论,而源是空的。

<div class="container">
<p class="lead custom_bg" id="comment"> updateme!
    <code id="source"> updateme2!</code>
</p>
</div>

jQuery 技术

success: function(response){
         $('#comment').text(response['comment']);
         $('#source').text(response['source']);
     }

据我了解,.text 属性似乎会更改该段落中的所有文本。

最佳答案

问题是因为通过设置 #commenttext() 你会破坏该元素中的所有 HTML,所以 #source 实际上已经不存在了。

要解决此问题,您只需更改 #comment 中第一个文本节点的值,如下所示:

var response = {
  comment: 'comment',
  source: 'source'
}

$('#comment').contents()[0].nodeValue = response['comment'];
$('#source').text(response['source']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <p class="lead custom_bg" id="comment"> updateme!
    <code id="source"> updateme2!</code>
  </p>
</div>

或者,您可以将目标文本包装在它自己的 span 中,这样可以直接定位,如下所示:

var response = {
  comment: 'comment',
  source: 'source'
}

$('#comment span').text(response['comment']);
$('#source').text(response['source']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <p class="lead custom_bg" id="comment"> 
    <span>updateme!</span>
    <code id="source"> updateme2!</code>
  </p>
</div>

关于javascript - 更改段落 jQuery 中的内部值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45836608/

相关文章:

javascript - jQuery:显示隐藏部分并导航到 anchor

javascript - 在 vb.net 中将多个变量传递给 javascript onclick

javascript - QuaggaJs:条码扫描仪的浏览器兼容性问题

javascript - jquery检查时间是否过期

html - html表格行的行计数器

javascript - websocket (NODEJS) 的僵尸 session ?

php - 如何使用mysqli_real_escape_string来存储由json ajax解析的数组?

php - 2 个不同的服务器如何在同一个 "machine"中通信?

html - 悬停时图像摆动(比例效应)

html - 使用一些 css 技术以正确的格式显示 html 表格?