js執行個體
| 代碼如下 |
複製代碼 |
|
<style type="text/css">
*{margin:0;padding:0;}
.demonstrate{padding:20px;}
.description h3{color:#900;padding:8px 0;}
.description p{ line-height:23px;}
#demo{width:550px;padding:5px;border:1px #f00 solid;float:left;}
#demo a{width:100px; height:100px; background:#9CF;float:left;margin:5px;}
#demo >a:hover,#demo >a.active{ color:#fff;font-weight:bold;background:#F00;}
</style>
<script type="text/javascript">
window.onload=function(){
var demo=document.getElementById("demo");
var children=demo.getElementsByTagName("a");
var num=0;
for(var i=0;i<children.length;i++){
children[i].index=i;//保留當前點擊項所在索引值
children[i].onclick=function(){
children[num].className="";
this.className="active";
num=this.index;
}
}
}
</script>
<!--執行個體效果文字描述,可刪-->
<div class="demonstrate">
<div class="description">
<h3>實現jq遍曆元素更改class屬性的原生js寫法</h3>
<p>實現效果:點擊當前項添加class名:active,其它同級項移除該class名</p>
<p>實現原理:設定一變數(執行個體是num)用於記錄當前點擊項的所在索引值,當發生點擊事件時先去掉原先記錄到索引值對應項的class名,再為當前點擊項添加class名!關鍵是點擊項所在索引值的記錄!</p>
</div>
<!--執行個體效果文字描述,結束-->
<div id="demo">
<a href="#" class="active">item1</a>
<a href="#">item2</a>
<a href="#">item3</a>
<a href="#">item4</a>
<a href="#">item5</a>
<a href="#">item6</a>
<a href="#">item7</a>
<a href="#">item8</a>
<a href="#">item9</a>
<a href="#">item10</a>
</div>
</div>
|
JQuery遍曆1:CssClass遍曆元素
將所有的checkbox設定為未選中,採用遍曆的方法來完成
控制項如下
| 代碼如下 |
複製代碼 |
|
<button id="ClearPosition" type="button">清空職位</button>
<input type="checkbox" class="jobPostaJoblist"/><span>導購/促銷</span>
<input type="checkbox" class="jobPostaJoblist"/><span>收銀員</span>
<input type="checkbox" class="jobPostaJoblist"/><span>店長</span> |
JQUERY代碼如下:
jobPostaJoblistSelected是checkbox被選中時的css
stopDefault函數用於中止預設的事件響應
| 代碼如下 |
複製代碼 |
|
$("#ClearPosition").each(function(i) {
$(this).click(function(e) {
$("input[class*='jobPostaJoblist']").each(function(i) {
$(this).attr("checked", false);
$(this).next().removeClass("jobPostaJoblistSelected");
});
return stopDefault(e);
});
});
function stopDefault(e) {
if (e && e.preventDefault) {
e.preventDefault();
} else {
window.event.returnValue = false;
}
return false;
}
|