使用jQuery .append()在<p>内添加<strong>并保留后续文本的问题
问题:jQuery动态渲染DOM时
标签内文本无法跟随标签显示
目标要渲染的DOM结构:
<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" style="color: white" aria-label="Close"> <span aria-hidden="true">×</span> </button> <p> <strong>Error!</strong> My error message </p> </div>
尝试用jQuery .append() 渲染上述结构时,无法让<p>标签的文本出现在<strong>标签之后——文本要么在<strong>之前,要么直接覆盖<strong>标签内容。
尝试的代码:
$('#error-div').append( $('<div>').prop( { class: 'my-class-name', role: 'alert', } ).append( $('<button>').prop({ type: 'button', class: 'close', style: 'color: white', }).attr( { 'data-dismiss': 'alert', 'aria-label': 'Close' } ).append( $('<span>').attr( { 'aria-hidden': true, }).html('×') ) ).append( $('<p>').append( $('<strong>').html('Error! ') ).html('My error message') ))
实际渲染结果:
<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close" style="color: white;"> <span aria-hidden="true">×</span> </button> <p>My error message</p> </div>
请问如何实现让<strong>标签位于<p>标签内部,且<p>的文本在<strong>之后?
解决方案
错误原因
你在给<p>标签先append()了<strong>元素后,又调用了.html('My error message')——这个方法会直接替换<p>标签内的所有现有内容,包括之前添加的<strong>,所以导致<strong>被覆盖消失。
正确写法
写法1:用.append()追加文本
保持链式调用,给<p>先添加<strong>,再用.append()追加文本内容:
$('#error-div').append( $('<div>').prop({ class: 'alert alert-danger alert-dismissible', role: 'alert', }).append( $('<button>').prop({ type: 'button', class: 'close', style: 'color: white', }).attr({ 'data-dismiss': 'alert', 'aria-label': 'Close' }).append( $('<span>').attr({ 'aria-hidden': true, }).html('×') ) ).append( $('<p>').append( $('<strong>').html('Error! ') ).append(' My error message') // 用append追加文本,而非覆盖 ) );
写法2:直接设置<p>的HTML内容
如果结构简单,也可以直接把<strong>和文本一起作为HTML内容传给.html():
$('#error-div').append( $('<div>').prop({ class: 'alert alert-danger alert-dismissible', role: 'alert', }).append( $('<button>').prop({ type: 'button', class: 'close', style: 'color: white', }).attr({ 'data-dismiss': 'alert', 'aria-label': 'Close' }).append( $('<span>').attr({ 'aria-hidden': true, }).html('×') ) ).append( $('<p>').html('<strong>Error! </strong> My error message') ) );
写法3:分步构建(更易维护)
把DOM元素拆分构建,逻辑更清晰:
// 构建关闭按钮 const closeBtn = $('<button>') .prop({ type: 'button', class: 'close', style: 'color: white' }) .attr({ 'data-dismiss': 'alert', 'aria-label': 'Close' }) .append($('<span>').attr('aria-hidden', true).html('×')); // 构建带strong的p标签 const errorPara = $('<p>') .append($('<strong>').text('Error! ')) .append('My error message'); // 构建alert容器并添加到目标元素 const alertDiv = $('<div>') .prop({ class: 'alert alert-danger alert-dismissible', role: 'alert' }) .append(closeBtn) .append(errorPara); $('#error-div').append(alertDiv);
核心要点
避免用.html()覆盖已有内容,如果需要追加元素或文本,使用.append()方法——它会把新内容添加到目标元素的末尾,保留原有内容。
内容的提问来源于stack exchange,提问作者GH DevOps
相关产品推荐
相关产品推荐

