一些应该熟记于心的jQuery函数和技巧

发表于:2011-1-19 10:00

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:司马牵牛 译    来源:51Testing软件测试网采编

#
java
#
JAVA
#
Java
#
jquery
#
jQuery

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

  高级选择器(selector)

  在jQuery中,我们可以使用各种各样的选择器,这使得选择器的使用变得非常精确。下面我们来一步一步地讲解这些选择器并看看在其他语境中如何使用这些选择器。

  基于属性的选择器

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

  • <img src="" alt="" width="" height="" border="0" /> 
  • <input type="text" name="email" value="" size="80" />
  •   上面两个HMTL元素中包含了九个属性。利用jQuery,我们可以根据元素的属性和属性值来对元素进行选择。一起看看以下例子中的选择器:

  • $(document).ready(function(){  
  •     //Alltheimageswhosewidthis600px  
  •     $("img[width=600]").click(function(){  
  •        alert("You'vejustselectedanimagewhosewidthis600px");  
  •      });  
  •   //Alltheimageshavingawidthdifferentto600px  
  •     $("img[width!=600]").click(function(){  
  •         alert("You'vejustselectedanimagewhosewidthisnot600px");  
  •     });  
  •  //Alltheinputswhosenameendswith'email'  
  •      $("input[name$='email']").focus(function(){  
  •        alert("Thisinputhasanamewhichendswith'email'.");  
  •     });  
  • });
  •   在官方文档中,我们可以看到许多选择器与上例中的选择器非常类似。但关键点是一样的,属性和属性值。

      多重选择器

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

  • $(document).ready(function(){   
  •     //Alltheimageswhosewidthis600pxORheightis400px  
  •     $("img[width=600],img[height=400]").click(function(){  
  •        alert("Selectedanimagewhosewidthis600pxORheightis400px");  
  •     });  
  •   //Allpelementswithclassorange_text,divsandimages.  
  •     $("p.orange_text,div,img").hover(function(){  
  •          alert("Selectedapelementwithclassorange_text,adivORanimage.");  
  •     });   
  •  //Wecanalsocombinetheattributesselectors  
  •     //Allthejpgimageswithanaltattribute(thealt'svaluedoesn'tmatter)  
  •     $("img[alt][src$='.jpg']").click(function(){  
  •        alert("Youselectedajpgimagewiththealtattribute.");  
  •      });  
  • });
  •   Widget组件选择器

      除了插件的选择器之前,还有一些基于元素某些属性或位置的选择器。下面让我们看看这些更为重要的选择器:

    41/41234>
    《2023软件测试行业现状调查报告》独家发布~

    关注51Testing

    联系我们

    快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

    法律顾问:上海兰迪律师事务所 项棋律师
    版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
    投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

    沪ICP备05003035号

    沪公网安备 31010102002173号