JQuery :contains function limit to exact match

ぃ、小莉子 提交于 2019-11-28 13:34:54

Try using .filter(), to find the option you want.

$('option').filter(function(){
    return $(this).html() == "<?php echo $_SESSION['divelevel'];?>";
}).attr('selected', 'selected');

Rocket Hazmat's answer was able to help me on my current project, where a cookie value is set and the table row that that cookie value pertains to needs to be highlighted. The code I originally had was:

$(".datalist TBODY TR:has('TD.itemId:contains(" + activeRowCookie + ")')").attr('id', 'activeRow');

Which worked fine until we realized that a table cell could contain the activeRowCookie value plus other characters, but we needed an exact match to the entire contents of the cell. Also, we are looking for the cell that contains that exact value and no more but then we highlight the row that cell is in, not just the cell itself. So I got it to work by adapting the answer here to the following:

$('.datalist TBODY TR TD.itemId').filter(function () {
  return $(this).text() == activeRowCookie;
}).parent().attr('id', 'activeRow');

And, yes, that initial selector does need to be like that because we don't want it looking at cells in the THEAD element.

Try add a extend pseudo function:

$.expr[':'].textEquals = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().match("^" + arg + "$");
    };
});

Then you can do:

$('p:textEquals("<?php echo $_SESSION['divelevel'];?>")').attr('selected', 'selected');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!