定位精确文本匹配(jQuery)

时间:2013-01-25 00:19:27

标签: jquery filter match target

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

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/

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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();