2013-01-25 55 views
2

我需要通过确切的文本匹配来定位多个类。我的代码似乎有一半的工作(文本具有一个紫色的背景时复选框取消选中),但勾选复选框为目标的文本时,似乎没有任何要发生的事情......针对精确的文本匹配(jQuery)

if ($("input:checkbox:checked#checkbox-id").length > 0) { 
     $('#main-content-panel .entry').filter(function(index) { 
     return $(this).text() == "Text"; }).css 
     ('backgroundColor', 'orange'); 
     } 

if ($("input:checkbox:not(:checked)#checkbox-id").length > 0) { 
     $('#main-content-panel .entry').filter(function(index) { 
     return $(this).text() == "Text"; }).css 
     ('backgroundColor', 'purple'); 
     } 

的jsfiddle:http://jsfiddle.net/KKfEF/

+0

你还没有得到一个触发事件,对复选框的变化?你想要发生什么? – mattytommo

+0

用我想说的第一块代码,“如果复选框被选中,将背景颜色更改为橙​​色”。 – Chris

回答

4

你应该听change事件:

var $elem = $('#main-content-panel .entry').filter(function (index) { 
    return $(this).text() == "Text"; 
}); 
$('#checkbox-id').change(function() { 
    var color = this.checked ? 'orange' : 'purple'; 
    $elem.css('backgroundColor', color); 
}).change(); 

http://jsfiddle.net/drcpY/

+0

作品在小提琴中很棒,但在我的代码中没有任何事情发生时,我检查框......嗯...... – Chris

+0

@Chris你把你的代码放在文档准备好处理程序中吗? – undefined

+0

是的,不幸的是它没有帮助:/感谢您的建议和帮助,还有什么可以防止这种情况发生? – Chris

1

你忘了加一个onchange事件处理器。

onchange="run()"> 

裹在功能过于你的代码,像这样

run = function() { 
if ($("input:checkbox:checked#checkbox-id").length > 0) { 
      $('#main-content-panel .entry').filter(function(index) { 
      return $(this).text() == "Text"; }).css 
      ('backgroundColor', 'orange'); 
      } 

if ($("input:checkbox:not(:checked)#checkbox-id").length > 0) { 
      $('#main-content-panel .entry').filter(function(index) { 
      return $(this).text() == "Text"; }).css 
      ('backgroundColor', 'purple'); 
      } 
} 
run(); 
+0

感谢您的代码,我给它一个去,但没有运气? http://jsfiddle.net/drcpY/1/ – Chris

+1

你错误地复制了代码,并没有把onchange事件处理程序放进去。http://jsfiddle.net/drcpY/2/ –

+0

啊,谢谢你的小提琴。您的建议在小提琴中运行良好,但又不在我的代码中,不知道为什么。我必须从另一个角度解决我的问题。谢谢你的时间。 – Chris