繁体   English   中英

如何使用jQuery在某些字符串之前和之后添加HTML标签

[英]How to add html tags before and after certain string using jquery

我有以下HTML:

<h5 class="pi-accordion-title">
    <a href="#" class="z">
        <span class="pi-accordion-toggle"></span>
            My Link (Keyword)
    </a>
</h5>

这是手风琴链接的一部分。 我想做的是在(关键字)之前打开span标签,然后在它之后关闭它。

我正在尝试以下JAVASCRIPT:

<script>
    $("(Keyword)").before("<span class='orange'>"); 
    $("(Keyword)").after("</span>");         
</script>

但是它不起作用...控制台日志显示以下错误:语法错误,无法识别的表达式:(关键字)

您无法使用jQuery选择这样的文本。 这是一种非常简单的方法, 甚至不需要jQuery

这种方法的缺点是容器的整个内容都将被重写,这意味着如果要将事件附加到容器的某些子代上,则必须在插入跨度之后执行此操作。 因此,我建议选择一个尽可能小的容器。

var toReplace ='(关键字)'; var container = document.getElementsByClassName(“ pi-accordion-title”); Array.prototype.forEach.call(containers,function(container){container.innerHTML = container.innerHTML.replace(toReplace,'$&');});;

.pi-accordion-title a span {
  color:red;
}
<h5 class="pi-accordion-title">
    <a href="#" class="z">
        <span class="pi-accordion-toggle"></span>
            My Link (Keyword)
    </a>
</h5>

编辑

如果要避免上述元素覆盖的缺点,可以利用":contains" jQuery选择器。 如果您使用的是jQuery我实际上认为它是最好/最安全的方法,因为您只会重写父元素。

var toReplace = '(Keyword)';
$(":contains(" + toReplace + ")").each(function(){
  this.innerHTML = this.innerHTML.replace(toReplace, '<span>$&</span>');
});
.pi-accordion-title a span {
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h5 class="pi-accordion-title">
    <a href="#" class="z">
        <span class="pi-accordion-toggle"></span>
            My Link (Keyword)
    </a>
</h5>
$('.pi-accordion-title').each(function() {
    this.innerHTML = this.innerHTML.replace(/(\(Keyword\))/, '<span class="orange">$1</span>');
});

我试过用jquery。获取类名并获取文本或html,然后可以用.replace替换为find word

var title = $(".pi-accordion-title");
var text = title.html();
title.html(text.replace(/(\(Keyword\))/g,"<span class='orange'>$&</span>"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM