00_jQuery常用-一些应该熟记于心的jQuery函数和技巧-01

【51CTO独家特稿】现在使用jQuery的网站数不胜数,它能够成为成最为知名的JavaScript框架,肯定存在着某种原因。作为开发者,我们必须更深入地思考问题,应该能够使用每一种我们想要了解的语言和框架所具有最高级技巧。

关于jQuery更多内容,欢迎访问: jQuery从入门到精通

高级选择器(selector)

在jQuery中,我们可以使用各种各样的选择器,这使得选择器的使用变得非常精确。51CTO也曾经和读者分享过jQuery选择器深入分析:避免不必要的调用,下面我们来一步一步地讲解这些选择器并看看在其他语境中如何使用这些选择器。

基于属性的选择器

在HTML中,几乎所有元素都具有属性,比如:

  1. <img src="" alt="" width="" height="" border="0" /> 
  2. <input type="text" name="email" value="" size="80" /> 

上面两个HMTL元素中包含了九个属性。利用jQuery,我们可以根据元素的属性和属性值来对元素进行选择。一起看看以下例子中的选择器:

  1. $(document).ready(function(){  
  2.  
  3.     //Alltheimageswhosewidthis600px  
  4.  
  5.     $("img[width=600]").click(function(){  
  6.  
  7.        alert("You'vejustselectedanimagewhosewidthis600px");  
  8.  
  9.     });  
  10.  
  11.   //Alltheimageshavingawidthdifferentto600px  
  12.  
  13.     $("img[width!=600]").click(function(){  
  14.  
  15.         alert("You'vejustselectedanimagewhosewidthisnot600px");  
  16.  
  17.     });  
  18.  
  19.  //Alltheinputswhosenameendswith'email'  
  20.  
  21.     $("input[name$='email']").focus(function(){  
  22.  
  23.        alert("Thisinputhasanamewhichendswith'email'.");  
  24.  
  25.     });  
  26.  
  27. }); 

在官方文档中,我们可以看到许多选择器与上例中的选择器非常类似。但关键点是一样的,属性和属性值。

多重选择器

如果你开放的是一个较为大型的网站,选择器的使用会变得困难。有时为了让代码变得更为简单,最好将它们分割为两个或三个选择器。实际上这是非常简单和基础的知识,不过非常有用,我们应该把这些知识熟记于心。

  1. $(document).ready(function(){  
  2.  
  3.     //Alltheimageswhosewidthis600pxORheightis400px  
  4.  
  5.     $("img[width=600],img[height=400]").click(function(){  
  6.  
  7.        alert("Selectedanimagewhosewidthis600pxORheightis400px");  
  8.  
  9.     });  
  10.  
  11.  //Allpelementswithclassorange_text,divsandimages.  
  12.  
  13.     $("p.orange_text,div,img").hover(function(){  
  14.  
  15.         alert("Selectedapelementwithclassorange_text,adivORanimage.");  
  16.  
  17.     });   
  18.  
  19. //Wecanalsocombinetheattributesselectors  
  20.  
  21.     //Allthejpgimageswithanaltattribute(thealt'svaluedoesn'tmatter)  
  22.  
  23.     $("img[alt][src$='.jpg']").click(function(){  
  24.  
  25.        alert("Youselectedajpgimagewiththealtattribute.");  
  26.  
  27.     });  
  28.  
  29. }); 

posted on   shao  阅读(173)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示