using a variable in :contains - how to

纵然是瞬间 提交于 2020-01-05 07:10:36

问题


I am using accordion menu on an e-commerce site. The menu stays open with the options until the product page. On that page I am trying to use the breadcrumbs to match text in the menu and then apply a class to open the menu to the correct category for the page.

Here is my code:

$(document).ready(function(){
 var bctext = $('#ProductBreadcrumb ul li:last-child').prev('li').children().text();
$('ul#accordion a:contains(bctext)').parent().parent().addClass('special');

 });

The variable returns the correct text, and if I put a matching string ("Tomato Sauces") in the :contains it works just like I want it to and applies the class. However when I use bctext variable it wont work.

I also tried a:contains($(bctext)) and it didn't work. Is it my syntax?

Thanks


回答1:


Try:

$('ul#accordion a:contains(' + bctext + ')')



回答2:


You could use Traversing/contains also:

$('ul#accordion a').contains(bctext);



回答3:


Change:

$('ul#accordion a:contains(bctext)').parent().parent().addClass('special');

to:

$('ul#accordion a:contains(' + bctext + ')').parent().parent().addClass('special');

The first way, the way you had it, is telling JavaScript to use the string 'bctext' as the contains parameter. What you actually want is the string which is contained within the bctext variable. Therefore you have to use it outside of the quotes and use concatenation to create your selector string.




回答4:


$('ul#accordion a').filter(':contains(' + bctext + ')'  

is now preferred to the deprecated

$('ul#accordion a').contains(bctext); 

(as commented by Crescent Fresh)




回答5:


This line should be:

$('ul#accordion a:contains(' + bctext + ')').parent().parent().addClass('special');



回答6:


This is a special-character-save version, that uses filter instead of the deprecated contains method.

$('ul#accordion a').filter(function () { return $(this).text() == bctext; })



来源:https://stackoverflow.com/questions/1274710/using-a-variable-in-contains-how-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!