自学内容网 自学内容网

JQuery基本操作(二)

遍历
$(选择器).each(function(下标,值){
                //代码块
});

$.each(数组名,function(下标,值){
                //代码块
});
<body>
  <button> 获得数组下标和值</button>
</body>
<script>
  $(function(){
    $("button").click(function(){
      var arr = [1,2,3,4,5,6];
      $.each(arr,function(index,value){
        console.log("下标:"+index+" 值:"+value);
      });
    });
  });
</script>

判断是否包含指定的样式 
$(".div1").hasClass("div2")
<style>
  .div1{
    width:100px;
    height:100px;
    background-color: #008000;
    font-size: 20px;
  }
  .div2{
    color: white;
  }
</style>

<body>
  <div class="div1">aaa</div>
  <button>判断是否包含指定的样式</button>
</body>
<script>
  $(function(){
    $("button").click(function(){
      if(!$(".div1").hasClass("div2")){
        $(".div1").addClass("div2");
      }else{
        $(".div1").removeClass("div2");
      }
    });
  });
</script>

表单提交事件
$(选择器).submit(function(){
return true;  //true提交  false禁止提交
});
<body>
  <form id="userForm" method="get" action="1111" >
    用户名:<input type="text" id="userName" placeholder="请输入用户名"/>
    <br />
    密码:<input type="text" id="password" placeholder="请输入密码"/>
    <br />
    <input type="submit" value="提交" />
  </form>
</body>
<script>
  $(function(){
    
    $("#userForm").submit(function(){
      alert("登录成功!")
      return false;
    })
  })
</script>

单击事件
$(选择器).click(function(){
});
键盘按下事件(keydown)
$(window).keydown(function(k){
        k.keyCode   //获取键盘按下后对于的键值
});
<body>
  备注:
  <textarea maxlength="10"></textarea>
  <span>0</span>/10
  
</body>
<script>
  $(function(){
    $("textarea").keydown(function(){
      $("span").text($(this).val().length);
    }).keypress(function(){
      $("span").text($(this).val().length);
    }).keyup(function(){
      $("span").text($(this).val().length);
    });
  });
</script>

光标事件
//获取光标事件
$(选择器).focus(function(){
});

//光标离开事件
$(选择器).blur(function(){
});
<body>
<input type="text" placeholder="请输入" id="111" />
</body>
<script>
$(function(){
$("#111").focus(function(){
    alert("移入!");
});
    $("#111").blur(function(){
    alert("移出!");
});
});
</script>

动态生成元素,并绑定事件(on)
$("body").on(要绑定的事件,目标元素,函数);
<body>
  <ul>
    <li>aaa</li>
    <li>bbb</li>
    <li>ccc</li>
    <li>ddd</li>
  </ul>
  <button>添加元素</button>
</body>
<script>
  $(function(){
    $("body").on("click","li",function(){
      $(this).css("color","red");
    });
    $("button").click(function(){
      $("ul").append("<li>eee</li>");
    });
  });
</script>


原文地址:https://blog.csdn.net/m0_71192988/article/details/142882231

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!