我的代码
我有这个html
<a href="#">
<i>[please keep this]</i>
Some Text To Update
</a>
还有这个 jQuery
$('a').click(function(){
$(this).text('Updated Text');
return false;
});
问题
当点击链接时,我得到:
<a href="#">Updated Text</a>
期望的结果
我想保留 <i>
元素并得到这个:
<a href="#"><i>[please keep this]</i> Updated Text</a>
无法修改 HTML
play along on jsFiddle
最佳答案
最好的方法如下:
添加跨度:
<a href="#">
<i>[please keep this]</i>
<span class="replace">Some Text To Update</span>
</a>
$('a').click(function(){
$('.replace', this).text('Updated Text');
return false;
});
在span
内添加您的文本,然后更新您的span文本。
不修改html:
$('a').click(function(){
$(this).html(function(i, text) {
return text.substr(0, text.lastIndexOf('>') + 1) + 'Updated Text';
});
return false;
});
或
$('a').click(function(){
var $keep = $('i', this);
$(this).empty().append($keep).append('Updated Text');
});
关于jquery - 如何使用 jQuery 更新元素的文本节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11788879/