根据链接文本的内容添加类

Adding class based on contents of link text

本文关键字:添加 链接 文本      更新时间:2023-09-26

我在 Stack 上找到了一个不错的片段,它从链接中获取文本并将其作为类附加到 a 标签中:

$('a.nav').each(function() {
    // add class with name of the link's text
    $(this).addClass($(this).text());
});

它工作得很好,除了我有一个链接搜索结果列表,这些搜索结果在链接文本之后输出(numbers), e.g. (19)

因此,在应用上述 JQuery 之后,我的 HTML 结构是这样的:

<li><a class="Basic page (1)" href="#">Basic page (1)</a></li>
<li><a class="Blog (19)" href="#">Blog (19)</a></li>
<li><a class="News (4)" href="#">News (4)</a></li>

如您所见,这并不理想。如果可能的话,我想至少去掉括号中的数字,即 (1)(19)等...然后加上破折号,并带有文本和小写。请注意,这是针对分面搜索结果的,因此链接永远不会全部在一起或顺序相同。 我只是尝试根据链接文本名称应用动态类,以便我可以在主题领域做其他事情。

所以这个:

<li><a class="Basic page (1)" href="#">Basic page (1)</a></li>

。会变成这样:

<li><a class="basic-page" href="#">Basic page (1)</a></li>

一些基本的正则表达式将获得您正在寻找的格式。

$('a.nav').each(function() {
    // add class with name of the link's text
    $(this).addClass($(this).text()
        .toLowerCase()
        .replace(/('s'('d+'))/, '') // replaces ' ([digit(s)])'
        .replace(/'s+/g, '-')); // replaces spaces with dashes
});

尝试如下操作,

演示

$(function() {
    $.each($('ul li a'), function() {
        var text = $(this).text();
        this.className = $.trim(text.replace(/'('d*')/g, '').toLowerCase()).replace(/'s/, '_');
    });
});

我在这里找到了一个小函数。在它的帮助下,我想下面的代码将为您工作;

.HTML:

<ul>
  <li><a href="#" class="nav">Basic page (1)</a></li>
  <li><a href="#"class="nav">Blog (19)</a></li>
  <li><a href="#"class="nav">News (4)</a></li>
</ul>

Javascript:

function string_to_slug(str) {
  str = str.replace(/^'s+|'s+$/g, ''); // trim
  str = str.toLowerCase();
  // remove accents, swap ñ for n, etc
  var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
  var to   = "aaaaeeeeiiiioooouuuunc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }
  str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
    .replace(/'s+/g, '-') // collapse whitespace and replace by -
    .replace(/-+/g, '-'); // collapse dashes
  return str;
}
jQuery(function($) {
    $('a.nav').each(function() {
        // add class with name of the link's text
        $(this).addClass(string_to_slug($(this).text()));
    });
});

示例:http://jsfiddle.net/CjdsG/

$('a.nav').each(function() {
    var oSelf = $(this);
    var sClass = oSelf.html()
        .toLowerCase()
        .replace(/('w)('W'([0-9]+'))/, '$1')
        .replace(' ', '-');
    oSelf.addClass(sClass);
});