jquery 的冷知识,自定义选择器。
代码如下:
// HTML 代码
<body>
<div id="divid1" class="divclass">白色</div>
<div id="divid2" class="divclass">白色</div>
<div id="divid3" class="divclass">白色</div>
<div id="divid4" class="divclass">白色</div> <p style="width:500px;">
<input type="button" value="按钮[绿色]" id="but1" />
<input type="button" value="按钮[红色]" id="but2" />
<input type="button" value="按钮[蓝色]" id="but3" />
<input type="button" value="按钮[黄色]" id="but4" />
</p> <script type="text/javascript">
// 初始化自定义选择器
$(function () {
$.expr[":"].greenbg = function (obj) {
if (obj.style.backgroundColor === "green")
return $(obj).css("background-color", "white"), $(obj).text("白色");
return $(obj).css("background-color", "green"), $(obj).text("绿色");
};
$.expr[":"].redbg = function (obj) {
if (obj.style.backgroundColor == "red")
return $(obj).css("background-color", "white"), $(obj).text("白色");
return $(obj).css("background-color", "red"), $(obj).text("红色");
};
$.expr[":"].blackbg = function (obj) {
if (obj.style.backgroundColor == "blue")
return $(obj).css("background-color", "white"), $(obj).text("白色");
return $(obj).css("background-color", "blue"), $(obj).text("红色");
};
$.expr[":"].yellowbg = function (obj) {
if (obj.style.backgroundColor == "yellow")
return $(obj).css("background-color", "white"), $(obj).text("白色");
return $(obj).css("background-color", "yellow"), $(obj).text("黄色");
}; });
// 使用自定义选择器
$("#but1").click(function () {
$("#divid1:greenbg");
});
$("#but2").click(function () {
$("#divid2:redbg");
});
$("#but3").click(function () {
$("#divid3:blackbg");
});
$("#but4").click(function () {
$("#divid4:yellowbg");
});
</script>