jQuery中易混淆知识点总结(持续更新)

find()与children()

<body>
	<ul class="level-1">
		<li class="item-i">I</li>
		<li class="item-ii">II
			<ul class="level-2">
				<li class="item-a">A</li>
				<li class="item-b">B
					<ul class="level-3">
						<li class="item-1">1</li>
						<li class="item-2">2</li>
						<li class="item-3">3</li>
					</ul>
				</li>
				<li class="item-c">C</li>
			</ul>
		</li>
		<li class="item-iii">III</li>
	</ul>
</body>

find

$(".level-2").find("li").css("border", "1px solid red");

结果:

children

$(".level-2").children().css("border", "1px solid red");

结果

结论:
两者都是用来寻找当前结点的后代元素,但children找的是直系(只向下找一级),find找的是所有的子孙后代;用法上,chilren不用跟参数,find则必须跟参数。

绑定与解绑事件

bind()

用法:
bind(eventType [, eventData ], handler)
handler是绑定到当前选中的元素,所以这些元素在调用bind之前必须存在
自jQuery3.0开始,已不建议使用

<body>
	<p>Click or double click here.</p>
	<span></span>
</body>
$("p").bind("click", function (event) {
    var str = "( " + event.pageX + ", " + event.pageY + " )";
    $("span").text("Click happened! " + str);
});


对于动态增加的元素,之前通过bind绑定的事件对它不起作用。例如:

$("body").append("<p>新增</p>");

live

用法:
live(events, handler)
描述:
Attach an event handler for all elements which match the current selector, now and in the future.
自jQuery1.7开始,已不建议使用

小结论:bind和live一次只能绑定一个事件,且都已不被建议使用。

delegate

用法:
delegate(selector, eventType, handler)
描述:
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
自jQuery3.0开始,已不建议使用

<body>
	<p>Click me!</p>
</body>
$("body").delegate("p", "click", function () {
    $(this).after("<p>Another paragraph!</p>");
});

结果:点击p都会产生新的"Another paragraph!",而对新产生的p标签点击之后也绑定了click事件。
点击原有的p标签

点击新生的p标签

on

用法:
on(events [, selector ] [, data ], handler)
描述:
Attach an event handler function for one or more events to the selected elements.

<body>
	<p>click me</p>
</body>
$("p").on("click select", function () {
    alert("attention");
});
$("body").append("<p>new one</p>");

结果

结论

函数名 可绑定的事件数 能对后添加元素绑定事件 jQuery建议版本
bind 1 不能 <=3.0
live 1 <=1.7
delegate <=3.0
on 不能 now

对应的解绑函数分别为 unbind() die() undelegate() off()

原文地址:https://www.cnblogs.com/caiyanhu/p/6900571.html