Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
根据jQuery中的html值选择元素_Jquery_Html_Jquery Selectors - Fatal编程技术网

根据jQuery中的html值选择元素

根据jQuery中的html值选择元素,jquery,html,jquery-selectors,Jquery,Html,Jquery Selectors,我有以下标记: 四, 五, 六, 如何选择html值为5和6的li项并向其添加类 使用选择器 $("ul.list li").each(function(){ if( $(this).text() == '5' || $(this).text() == '6' ) { $(this).addClass('theClass'); } }); $("li:contains('5')") 一个选择是 但是,由于它只是查找该文本,而不匹配整个内容,因此也将匹配56,16,等等 因

我有以下标记:
  • 四,
  • 五,
  • 六,

如何选择html值为5和6的li项并向其添加类

使用选择器

$("ul.list li").each(function(){
  if( $(this).text() == '5' || $(this).text() == '6' ) {
    $(this).addClass('theClass');
  }
});
$("li:contains('5')")
一个选择是

但是,由于它只是查找该文本,而不匹配整个内容,因此也将匹配
  • 56
  • 16
  • ,等等

    因此,您可能应该这样做:

    您可以使用
    .filter()

    如果返回
    true
    元素将保留在元素集中,如果返回false,则将从元素集中删除

    这将匹配元素的整个文本,而不仅仅是检查文本是否包含字符


    这里有一个演示:

    我怀疑这个演示过于简化了。。。你说的“值”是指文本

    $('.list li').filter(function(){
        var txt=$(this).text();
        return txt==='4' || txt==='5';                      
    }).addClass('someclass');
    

    也许会有帮助?请注意,这也会选择包含
    56
    5.1
    的列表项,或任何包含这些单个数字的项目。这只适用于只有单个数字的非常简单的情况。我不会投反对票,但您应该警告,这将匹配任何包含
    5
    的字符串或数字,如
    50
    5.0
    $("li").filter(function () {
        var text = $(this).text();
        return text === "5" || text === "6"
    }).addClass("myClassName");
    
    //setup object of the characters we want to match (we will be matching the keys, not values)
    var whitelist = { 5 : 0, 6 : 0 };
    
    //select all the list-item elements and filter them
    var $selectedElements = $('.list').children().filter(function () {
    
        //returns true if the text of this element is one of the keys in the `whitelist` variable
        return ($(this).text() in whitelist);
    });
    
    $('.list li').filter(function(){
        var txt=$(this).text();
        return txt==='4' || txt==='5';                      
    }).addClass('someclass');