无法使用jQuery定位多个单词

时间:2017-08-23 22:24:00

标签: javascript jquery html css jquery-ui

我正在尝试在网页上的特定文本周围添加span元素。这样我就可以使用jQuery's tooltip title attribute为某些单词添加工具提示。这个功能很适合它:

<label class="gfield_label">
    Clinicians provide contraception, including single-day LARC insertions, without requiring routine pelvic exams, cervical
    cancer screenings and STI results before offering contraception.
</label>

jQuery('.gfield_label').each(function() {
    var text = jQuery(this).text();
    jQuery(this).html(text.replace("LARC", "<span title='THIS BETTER WORK'>LARC</span>")); 

    $( function() {
        $( document ).tooltip();
    } );
});

但是,当尝试在不同<label>元素中定位多个关键字时,它会中断:

<label class="gfield_label">
    Clinicians provide contraception, including single-day LARC insertions, without requiring routine pelvic exams, cervical
    cancer screenings and STI results before offering contraception.
</label>

<br />
<br />
<br />
<label class="gfield_label">
    Clinicians provide contraception, including single-day LARC insertions, without requiring routine pelvic exams, cervical
    cancer screenings and STI results before offering contraception.
</label>

jQuery('.gfield_label').each(function() {
    var text = jQuery(this).text();
    jQuery(this).html(text.replace("LARC", "<span title='the tooltip for LARC'>LARC</span>")); 
    jQuery(this).html(text.replace("provide", "<span title='the tooltip for provide'>provide</span>"));
});

$( function() {
    $( document ).tooltip();
} );

有什么想法吗?这是codePen

编辑:我使用jQuery在HTML字词周围添加span元素,因为我无法访问HTML代码。

1 个答案:

答案 0 :(得分:0)

您覆盖使用原始text执行第二次replace时所执行的第一次替换。

这是一个修复:

&#13;
&#13;
jQuery('.gfield_label').each(function() {
    var text = jQuery(this).text();
    text = text.replace("LARC", "<span title='the tooltip for LARC'>LARC</span>")
    text = text.replace("provide", "<span title='the tooltip for provide'>provide</span>")
    jQuery(this).html(text);
});

$( function() {
    $( document ).tooltip();
} );
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<label class="gfield_label">
  Clinicians provide contraception, including single-day LARC insertions, without requiring routine pelvic exams, cervical
cancer screenings and STI results before offering contraception.
</label>

<br />
<br />
<br />
<label class="gfield_label">
  Clinicians provide contraception, including single-day LARC insertions, without requiring routine pelvic exams, cervical
cancer screenings and STI results before offering contraception.
</label>
&#13;
&#13;
&#13;

  

请注意,您的代码可能不适用于所有关键字,例如 - 如果您要替换单词LARC,则会尝试替换单词spantitle或{ {1}}它还会替换for中的字词,它会破坏你的HTML。