老生常谈jquery id选择器和class选择器的区别
实例如下:
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <title>Title</title> <linkhref="style.css"rel="externalnofollow"rel="externalnofollow"rel="stylesheet"type="text/css"/> <scripttype="text/javascript"src="jquery-2.1.4.js"></script> <scripttype="text/javascript"src="dams.js"> </script> </head> <body> <divclass="box">hello</div> <divclass="box">world</div> </body> </html> $(function(){ alert($('.box').size());//返回2 });
size()方法返回DOM对象的个数
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <title>Title</title> <linkhref="style.css"rel="externalnofollow"rel="externalnofollow"rel="stylesheet"type="text/css"/> <scripttype="text/javascript"src="jquery-2.1.4.js"></script> <scripttype="text/javascript"src="dams.js"> </script> </head> <body> <divid="box">hello</div> <divid="box">world</div> </body> </html> $(function(){ alert($('#box').size());//只能获得一个id=box的DOM对象,返回1 });
即:id是唯一的,即使有多个id相同的元素,jquery选择器也只能获取其中一个。所以:想在jquery中对id设置动作,id在页面中只允许出现一次。
对于CSS样式来说,可以选取页面中所有id=box的DOM对象:
#box{ color:red; };
jQuery选择器的写法和CSS选择器十分类似,但是功能却不同:
CSS找到元素后添加的是单一样式,而jquery添加的是动作行为。
以上这篇老生常谈jqueryid选择器和class选择器的区别就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。