JQuery :contains function limit to exact match

后端 未结 3 1253
走了就别回头了
走了就别回头了 2020-12-11 04:24

Using the JQuery :contains function to decide which option on a select is selected from a SESSION variable.

The contains function is matching the wrong option as the

相关标签:
3条回答
  • 2020-12-11 04:44

    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.

    0 讨论(0)
  • 2020-12-11 05:01

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

    $('option').filter(function(){
        return $(this).html() == "<?php echo $_SESSION['divelevel'];?>";
    }).attr('selected', 'selected');
    
    0 讨论(0)
  • 2020-12-11 05:01

    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');
    
    0 讨论(0)
提交回复
热议问题