http://api.jquery.com/category/selectors/

낮에 봄싹 그룹스에 자바스크립트 리팩토링을 부탁한다며 올렸던 코드입니다.

[javascript]
function showAttended() {
$(".memberItem").each(function(){
var arate = $(this).attr("arate");
var trate = $(this).attr("trate");
if(arate == 0 && trate == 0) {
$(this).hide();
} else {
$(this).show();
}
});
$("#attention-title").text("참석자");
}
function showNotAttended() {
$(".memberItem").each(function(){
var arate = $(this).attr("arate");
var trate = $(this).attr("trate");
if(arate == 0 && trate == 0) {
$(this).show();
} else {
$(this).hide();
}
});
$("#attention-title").text("불참자");
}
function showAll(){
$(".memberItem").each(function(){
$(this).show();
});
$("#attention-title").text("스터디 참석 신청자");
}
[/javascript]

원랜 올리고나서 번역에 집중을 할랬는데.. 갑자기 답멜로 코드가 쏟아지기 시작하더니.. 완전 멋진 코드까지 나오더군요.

[javascript]
function showAttended() {
$(".memberItem[arate=0][trate=0]").show();
$(".memberItem:not([arate=0][trate=0])").hide();
$("#attention-title").text("참석자");
}
function showNotAttended() {
$(".memberItem[arate=0][trate=0]").hide();
$(".memberItem:not([arate=0][trate=0])").show();
$("#attention-title").text("참석자");
}
function showAll() {
$(".memberItem").show();
$("#attention-title").text("스터디참석신청자");
}
[/javascript]

이용혁님께서 보내주신 코드인데 셀력터를 사용해서 제가 사용했던 each로 루프를 돌면서 li를 조적하던 코드 보다 훨씬 간결하고 코드도 직관적이라 이것으로 당첨!!

그런데 Outsider님께서 셀렉터 성능을 개선할 방법으로 find와 filter를 제시해 주셨죠. 그래서 결국 코드는 요렇게 바꼈습니다.

[javascript]
function showAttended() {
$(".memberItem").hide().filter(":not([arate=0][trate=0])").show();
$("#attention-title").text("참석자");
}
function showNotAttended() {
$(".memberItem").hide().filter("[arate=0][trate=0]").show();
$("#attention-title").text("불참");
}
function showAll() {
$(".memberItem").show();
$("#attention-title").text("스터디참석신청자");
}
[/javascript]

셀렉터를 잘 쓰면 each 같은걸 안써도 되니 더 직관적이고 깔끔한 코드를 만들 수 있더군요.

귿귿! 재미있는건 이 모든 피드백이 글을 올린지 불과 2시간 이내에 벌어졌다는거죠.

봄싹은 역시 멋져!!


[javascript]
$(".memberItem").each(function(){
var arate = $(this).attr("arate");
if(arate > 0){
$(this).css("border", "1px solid #4183C4");
}

var trate = $(this).attr("trate");
if(trate > 0){
$(this).css("background", "#E0F8F7 none repeat scroll 0 0");
}
});
[/javascript]

이 코드도 역시 셀력터를 사용하면 딱 두줄로 간추릴 수 있습니다. 고건.. 걍 퀴즈!