用$(this)缩小JQuery代码



我有以下代码:

$(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); 

这两个例子不起作用,但希望你能明白。

如果您想在单个链中执行所有这些操作,可以使用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);

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

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

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

最新更新