0

我有以下代码:

$(this).parent().find(".age").removeClass('active').children("input").prop('checked', false);
$(this).addClass('active').children('input').prop('checked', true); 

这行得通,但我想缩小它并做这样的事情:

$(this).parent().find(".age").removeClass('active').children("input").prop('checked', false).find(this).addClass('active').children('input').prop('checked', true); 

或者

$(this).parent().find(".age").removeClass('active').children("input").prop('checked', false).children(this).addClass('active').children('input').prop('checked', true); 

这两个示例不起作用,但希望您能理解。

4

2 回答 2

5

如果你想在一个链中执行所有这些操作,你可以使用end()来返回上一组匹配的元素:

$(this).parent().find(".age").removeClass("active")
                             .children("input").prop("checked", false).end()
                             .end()
                .end()
       .addClass("active").children("input").prop("checked", true);

另一种方式更清楚一点:

$(this).addClass("active").children("input").prop("checked", true).end()
       .parent().find(".age").removeClass("active")
                             .children("input").prop("checked", false);

也就是说,这些表达式非常复杂,坚持将它们链接起来可能会导致代码的可读性和可维护性降低。您的里程可能会有所不同,但与所有好事一样,不应滥用链接。

于 2013-08-22T07:28:05.083 回答
1

为什么不缓存$(this)到变量中:

var $this = $(this);
$this.parent().find(".age").removeClass('active')
.children("input").prop('checked', false);
$this.addClass('active').children('input').prop('checked', true); 
于 2013-08-22T07:27:56.880 回答