jQuery addClass基于属性值的元素

时间:2010-12-18 22:32:09

标签: jquery

我坚持这个并需要一些帮助。我知道这个的逻辑解决方案,但不知道如何将其转换为jQuery代码(这里是新手:))。任何建议或帮助非常感谢!

我需要将一个css类(活动类)添加到一个title属性等于变量值的元素中。所以,让我们说我的变量currentElement ='伟大的一天'。页面上还有一个标签元素,其标题属性为“大日”,例如<a title='great day' href='#'>

使用jQuery我想:在DOM中找到一个标签,其中currentElement ==标签标题并添加css类。所以,理想情况下它应该找到一个标签并将css类添加到它。

我想出了类似的东西但没有工作:

/* set currentElement var to the src attribute 
   value of an a tag on the page
   this works */
var currentElement = $('#greatLink'] img[src*=' + test + ']').attr('src');

/* now find an a tag on the page that has 
   the same title attribute as var currentElement
   this does not work */
$("a[title ='+currentElement+']").addClass('selectedThumb'); 

4 个答案:

答案 0 :(得分:8)

我认为您只需要将选择器更改为使用双引号而不是您拥有的嵌套单引号:

$( 'a[ title=' + currentElement + ']' ).addClass( 'selectedThumb' );

只需指出,选择器中属性的值不需要引用。 e.g。

$( 'a[ title="foo" ]' )

相同
$( 'a[ title=foo ]' )

整个选择器本身只是一个字符串。是否在上面的示例中引用值 foo 与结果无关。虽然引用该值可能看起来更“正确”,但由于没有必要,我发现更容易将其关闭。它几乎肯定会使你在诸如你的问题中不那么混乱,你在那里用可变值连接文字字符串。

答案 1 :(得分:1)

$('a[title="' + currentElement + '"]').addClass('selectedThumb');

答案 2 :(得分:1)

尝试

$("a[title ='"+currentElement+"']").addClass('selectedThumb');

注意额外的报价。

答案 3 :(得分:0)

$('[title='+currentElement+']').addClass('yourclass');
相关问题