如何替换"li"中的文本

thr*_*ool 4 html javascript jquery

我有大约100页都有<ul>- 问题是,我需要将每个列表项包装在一个<span>.我已添加以下代码

<ul style="list-style-type: disc; margin-left: 40px; line-height: 140%;" _mce_style="list-style-type: disc; margin-left: 40px; line-height: 140%;">
    <li> ICD-10 transition </li>
    <li> Pricing transparency </li>
    <li>Patient and payor mix fluctuation<br>&nbsp;</li>
</ul>  

$(document).ready(function () {
    $("li").each(function (index) {
        $("li:nth-last-child(" + index + ")").append(" <span>" + $("li:nth-last-child(" + index + ")").text() + "</span>");
    });
});
Run Code Online (Sandbox Code Playgroud)

这是我得到的结果:

ICD-10过渡ICD-10过渡ICD-10过渡

定价透明度定价透明度定价透明

患者和付款人混合波动

患者和付款人混合波动患者和付款人混合波动

当我只希望代码运行一次并替换代码一次而不是两次时,代码被替换两次.我想知道如何解决这个问题,但更多的是为什么这首先发生在一起.该方法没有被调用两次 - 所以它为什么会发生.


非常感谢你们帮助我弄清楚!!! 我得到了它...

  $(document).ready(function () {

        $("li").each(function (index) {
            $(this).html("<span>" + $(this).html() + "</span>");

        });
    });
Run Code Online (Sandbox Code Playgroud)

非常感谢你!!!!!!!!

Ibr*_*han 6

你可以像下面这样做.

$("li").each(function () {
    $(this).html('<span>'+$(this).html()+'</span>');
});
Run Code Online (Sandbox Code Playgroud)


Don*_*own 5

这种情况正在发生,因为当你附加span你保留文本时li,它会显示两次.您可以更改append()to html()清除其中的内容li并替换为new span:

$("li:nth-last-child(" + index + ")").html(" <span>" + $("li:nth-last-child(" + index + ")").text() + "</span>");
Run Code Online (Sandbox Code Playgroud)

工作演示