简体   繁体   English

jQuery如何根据其包含的文本添加一个类以跨越dl?

[英]jquery How do I add a class to span within a dl based on the text it contains?

I want to be able to add the class="st_sharethis" to the menu link: Tell A Friend on this site http://www.easyspacedesign.com/fh/ConnectBell_/ . 我希望能够将class =“ st_sharethis”添加到菜单链接:在此站点上告诉朋友http://www.easyspacedesign.com/fh/ConnectBell_/ There is no way to add a specific class or id to a menu link in the cms we use so going to have to use jquery to do it. 在我们使用的cms中,无法将特定的类或id添加到菜单链接中,因此必须使用jquery来完成。

So I will have to do it based on the text within the span tag that is within the a tag. 因此,我将不得不基于标签内的span标签内的文本来执行此操作。

So far i have tried: 到目前为止,我已经尝试过:

  $('.main_menu span:contains("Tell A Friend")').attr('class','st_sharethis');

  $('.main_menu span').each(function ()
  {
    if ($(this).text() == "Tell A Friend")
    $(this).attr('id','rev3');
  }

neither has worked. 都没有奏效。

If this menu item will always be latest one: 如果此菜单项始终是最新的:

$('#menu dl dt:last a').addClass('myclass');

Also, you have specific class last on this menu item, so you can: 另外,您在此菜单项last有特定的班级,因此您可以:

$('dt.last').addClass('myClass');

Or you can just test content of the link: 或者,您可以仅测试链接的内容:

$('#menu dl dt a span:contains("Tell A Friend")').parent().addClass('myClass');

The following adds a class and id to the element. 以下内容将一个类和id添加到该元素。

$('.main_menu span:contains("Tell A Friend")')
    .addClass('st_sharethis')
    .attr('id', 'rev3');

Your code is fine, you just need to add a ");" 您的代码很好,您只需添加“);” at the end! 在末尾!

 $('.main_menu span:contains("Tell A Friend")').attr('class','st_sharethis');

   $('.main_menu span').each(function ()
   {
     if ($(this).text() == "Tell A Friend")
     $(this).attr('id','rev3');
   }
 );   // ADD this line !

But of course it would be better to just chain the commands: 但是,当然最好只链接命令:

 $('.main_menu span:contains("Tell A Friend")')
  .attr('class','st_sharethis')
  .attr('id','rev3');

This works fine for your markup: 这适用于您的标记:

$('#menu span:contains("Tell A Friend")')
           .addClass('st_sharethis')
           .attr('id','rev3');

Live example: http://jsfiddle.net/ydFFR/ 实时示例: http//jsfiddle.net/ydFFR/

如果是最后一个,请尝试

$('a.main_menu.last').find('span').addClass('st_sharethis');

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

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