根据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');