我正在尝试在网页上的特定文本周围添加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代码。
答案 0 :(得分:0)
您覆盖使用原始text
执行第二次replace
时所执行的第一次替换。
这是一个修复:
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;
请注意,您的代码可能不适用于所有关键字,例如 - 如果您要替换单词
LARC
,则会尝试替换单词span
或title
或{ {1}}它还会替换for
中的字词,它会破坏你的HTML。