jq中稀有操作
- 查找祖先级标签
<div> //太爷爷级
<p> // 爷爷级
<span> //父级
<i>123</i>
</span>
</p>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
console.log($('i').closest('div')); // 查找确定名字的一个父级
console.log($('i').parent()); // 查找确定名字的一个父级 ,这里即 span
console.log($('i').parent()); //返回所有的祖先元素 . jQuery.fn.init(5) [span, p, div, body, html, prevObject: jQuery.fn.init(1)]
</script>
- 给动态元素绑定事件
这里着重说下click与on的区别:两者绑定静态元素都可以;但如果是动态创建的元素click是无效,只能使用on绑定动态的元素;
<div class="box"></div>
<button>按钮一</button>
<script>
$("button").on("click",function(){
$(".box").append("<button class='btn'>按钮二</button>")
})
$(".btn").click(function(e){
alert("吕星辰")
})
------------------------ 通过on来给动态元素绑定事件
$(document).on("click",function(e){
alert("吕星辰")
})
</script>
on 对同一个元素多次绑定同一个事件的时候,这个事件就会执行多次。
解决方法:遇到这种情况需要在每次绑定事件之前,对该事件解绑,也就是 $(‘’.test-btn’‘).off(’‘click’‘).on(’‘click’'); ,off方法解绑再on
$(function(){
$(".add").click(function(eve){
$(".btn-area").append("<button class='test-btn'>test button</button>");
//$(".test-btn").off("click");
$(".test-btn").on("click",function(){
console.log("test button .....");
});
});
});
- each
jQuery中的each() 就和原生js中的forEach() 很像
each()相当于jQuery中的 循环遍历用法
$.each(array,callback);
有两个参数 第一个是数组 或者对象 第二个是回调函数
函数里面可以有两个参数 function(index,item){}
第一个参数 是索引 第二个参数是 索引所对应的值
var arr = [ 1,2,3]
$.each(arr,function(index,value){
$('<div></div>').css({
width: 100,
height: 100,}).html(value)
.addClass('demo' + index).appendTo($('body'))
})
//或者第二种写法
//这里的$('li')是一个类数组
$('li').each(function(index,value){
$(value).addClass('demo' + index).html('哈哈哈').css({ backgroundColor: 'red', color: '#fff' })
})