我正试图检查一组id为"checkbox-selectro-chosen"的div,看看这些div中是否存在动态变量name。只有当存在一个"checkbox selector selected"div时,下面的代码才有效。我想做的是获得下面的代码,检查所有"复选框选择器选择"div是否存在名称。
if($(".checkbox-selector-chosen").text() == name) {
do something...
}
我正在使用的div的结构如下:
<div id="selected-results" class="group">
<div class="checkbox-selector-chosen">John</div>
<div class="checkbox-selector-chosen">Dave</div>
<div class="checkbox-selector-chosen">Jack</div>
</div>
我是JS/JQuery的新手,我相信这是一个简单的问题,但在我的头撞在桌子上两天后,我决定在这里提问。
任何帮助都将不胜感激!
您可能需要使用:contains((选择器来查看项目是否存在(JsFiddle Demo(
var name='Dave';
//Get all items that contain 'Dave'
var items = $(".checkbox-selector-chosen:contains('" + name + "')");
if (items.length > 0) {
alert(items.length + ' items found');
}
更新
如果您担心有多个匹配项,可以使用我的示例,AND each()
函数。(JsFiddle Demo(。这种方法的美妙之处在于,您不必循环遍历所有子div,只需要循环遍历包含所需匹配文本的div。
var name='Dave';
//Get all items that contain 'Dave'
var items = $(".checkbox-selector-chosen:contains('" + name + "')");
if (items.length > 0) {
items.each(function(){
if ($(this).html()==name){
alert('item found!');
break;
}
});
}
更新2
下面是一个示例,演示了该技术的充分使用。当你点击一个名称div时,这个名称会从被点击的对象中解析出来,我们使用上面的方法来找到合适的div。当然,这不是完成这个特定任务的最佳方式,但很简单地说明了这个概念。(JsFiddle Demo(
function findName(name){
var items = $(".checkbox-selector-chosen:contains('" + name + "')");
$('.checkbox-selector-chosen').css({'background':'#fff'});
if (items.length > 0) {
items.each(function(){
if ($(this).text()==name){
$(this).css({'background':'#ff0'});
}
});
}
}
$('.checkbox-selector-chosen').click(function(){
findName($(this).text());
});
您的类选择器返回匹配项的集合。您可以尝试each()
对它们进行迭代:
$(".checkbox-selector-chosen").each( function() {
if ($(this).text() == name) {
/* ..do something... */
} } );
$('.checkbox-selector-chosen').each(function(){
if($(this).text() == name) {
do something...
}
});
也许这就是你想要的?啊,被打败了!
您可以为此使用jquery'each'语法。
$(".checkbox-selector-chosen").each(function(index, value){
console.info("index = "+index +" = "+value);
if(value == name){
console.info("match");
}
});
您想要使用jQuery:contains((选择器。
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title></title>
</head>
<body>
<div id="selected-results" class="group">
<div class="checkbox-selector-chosen">John</div>
<div class="checkbox-selector-chosen">Dave</div>
<div class="checkbox-selector-chosen">Jack</div>
</div>
<script type="text/javascript">
jQuery(".checkbox-selector-chosen:contains(John)").css("background-color","red")
</script>
</body>
</html>
JSBIN
您可以使用contains()
选择器来过滤结果:
$('input[type="checkbox"]').change(function(){
var checked = this.checked;
$('.checkbox-selector-chosen')
.filter(":contains("+this.value+")")
.css('color',function(){
if (checked) return "red";
else return "black";
});
});
示例:http://jsfiddle.net/niklasvh/mww3J/