我有这段代码:
var pseudo = $('.user-pseudo').text();
if($(".view-poke .view-content div:contains('"+pseudo+"')").length) {
$(".view-poke .view-content div:contains('"+pseudo+"')").addClass('yeah');
}
我想将伪放入contains元素但它不起作用,不添加类。
感谢您的帮助!
答案 0 :(得分:0)
尝试:
console.log(pseudo);
然后硬编码伪的值并执行:
console.log($(".view-poke .view-content div:contains('hard-coded-value')"))
答案 1 :(得分:0)
请注意,:contains()
选择器为Case-sensitive
考虑以下fiddle
<span id="test1"> My pro text </span>
<span id="test2"> my pro text </span>
<span id="content"> I do have My pro text here </span>
$(function(){
var txt1 = $("#test1").text(); // My pro text
var txt2 = $("#test2").text(); // my pro text
var length1 = $("#content:contains('"+txt1+"')").length; // 1..
var length2 = $("#content:contains('"+txt2+"')").length; // 0..
})
替代方法:
要强制避免区分大小写的问题,您可以随时使用其他方法,例如
var pseudo = $('.user-pseudo').text();
$contentDivs = $(".view-poke .view-content div");
$contentDivs.each(function() {
var thisText = $(this).text().toLowerCase();
if (thisText.indexOf(pseudo.toLowerCase()) !== -1) {
// Div contains the pseudo text..
$(this).addClass('yeah');
}
else {
// Div doesn't contain pseudo text..
}
});