检查页面上是否有特定的字形图标,如果有——换成其他字形

check to see if a specific glyphicon is on the page, if so--change to something else

我正在尝试创建一个函数来检查页面上是否有特定的字形图标,如果是,我希望它显示其他内容。

这是我的代码,但运气不好

var span;
$('span').each(function(){
  if($(this).html() == 'glyphicon glyphicon-ok'){
    $(this).parent('li').html('✔').css({"color" : "blue"});
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="glyphicon glyphicon-ok"></span>

Jquery.attr()挽救一天的方法

通过使用.attr()方法我们可以获得元素的任何属性。

因此,通过使用:$(this).attr('class'),我们可以查看它是否与您要替换的字形匹配,并按照您的描述更改它的值。

Bellow 是一个工作示例。

var span;
$('span').each(function(){
  if($(this).attr('class') == 'glyphicon glyphicon-ok'){
    $(this).html('✔').css({"color" : "blue"});
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="glyphicon glyphicon-ok"></span>

$('.glyphicon-ok').each(
    function(){
         $(this).parent().html('✔').css({"color" : "blue"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="glyphicon glyphicon-ok"></span>

您可以使用jQuery hasClass() 函数来检查元素是否具有指定的class。这个函数returnstrue/false.

if($(this).hasClass("glyphicon-ok")) {
    // do something
}