jQuery之$(document)
$(document)是一个选择器,选中的是整个html所有元素的集合。
$(document).ready()里面的元素或事件都将会在DOM完成加载之后立即加载,并且在页面内容加载之前。
使用 $(document).ready(),你能让你的事件在window加载之前加载或触发。
jquery中用on来绑定事件,经常的写法有
on(events,[selector],[data],fn)
events:一个或多个用空格分隔的事件类型和可选的命名空间,如"click"或"keydown.myPlugin" 。
selector:一个选择器字符串用于过滤器的触发事件的选择器元素的后代。如果选择器为null或省略,当它到达选定的元素,事件总是触发。
data:当一个事件被触发时要传递event.data给事件处理函数。
$(document).on('click', '.classname', function() {});
$('.classname').on('click', function() {});
替换bind()
当第二个参数'selector'为null时,on()和bind()其实在用法上基本上没有任何区别了,所以我们可以认为on()只是比bind()多了一个可选的'selector'参数,所以on()可以非常方便的换掉bind();
<!DOCTYPE html>
<html> <head> <meta charset="utf-8" /> <title></title> <script src="static/utils/js/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script> <style> .classname{ width: 100px; height: 40px; line-height: 40px; background-color: #01AAED; border-radius: 10px; color: #FFFFFF; font-size: 12px; text-align: center; } .classimg{ width: 100px; height: 40px; line-height: 40px; background-color: #ff557f; border-radius: 10px; color: #FFFFFF; font-size: 12px; text-align: center; margin-top: 10px; } .bgimg{ background-color: #007DDB!important; } #list{ width: 100%; height: auto; } #list li{ width: 50px; height: 20px; background-color: #009688; margin-top: 5px; color: white; font-size: 12px; text-align: center; } </style> </head> <body> <div class="body"> <div class='classimg'>点击我</div> <div id="list"> <ul> <li> 123 </li> <li> 678 </li> </ul> </div> </div> <script type="text/javascript"> $(document).ready(function() { console.log("123") }); window.onload = function() { console.log("456"); } $(function() { console.log("789"); $(".body").prepend("<div class='classname'>点击我</div>") }) $(document).on('click', '.classname', function() { alert("被点击了") }); $('.classname').on('click', function() { alert("又被点击了") }); $(".classimg").bind("click",function(){ $(".classimg").addClass("bgimg") }); $(document).on('click', '#list li', function() { alert("又被点击了") }); </script> </body>
</html>
