JQuery

1个成员

Jquery遍历元素更改class属性

发表于 2017-01-27 2887 次查看
实现效果:点击当前项添加class名:active,其它同级项移除该class名 实现原理:设置一变量(实例是num)用于记录当前点击项的所在索引值,当发生点击事件时先去掉原先记录到索引值对应项的class名,再为当前点击项添加class名!关键是点击项所在索引值的记录!

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>


 

&nbsp;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;
          }

发表回复
你还没有登录,请先登录注册