使用$(this)缩小JQuery代码

use*_*299 0 jquery

我有以下代码:

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

这有效,但我想缩小它并做这样的事情:

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

或者

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

这两个例子不起作用,但希望你能得到这个想法.

Fré*_*idi 5

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

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

另一种方式是更清楚:

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

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