- 浏览: 516586 次
- 性别:
- 来自: 远方
文章分类
最新评论
-
futoviny:
挺有用的 javax.xml.ws.Holder
CXF学习笔记---让通过参数传递数据 -
zqb666kkk:
能提供下示例demo吗
CXF学习笔记---给CXF加一把锁WS_SECURITY应用 -
hello_world_wdq:
真是坑爹,这能用吗,害我半天时间浪费了
Extjs学习总结---RowExpander 的异步调用 -
ubuntu的疯狂:
第一段代码怎么用????求解释!!弄了很久还是不得结果……
Extjs学习总结---RowExpander 的异步调用 -
107x:
不错,谢谢分享!
[log4j]Slf4j的包冲突
jQuery and JavaScript Coding: Examples and Best Practices
By Smashing Editorial, September 16th, 2008 in How-To | 202 Comments | Forum
<!----> <noscript type="text/javascript"></noscript> <noscript></noscript>
When used correctly, jQuery can help you make your website more interactive, interesting and exciting. This article will share some best practices and examples for using the popular Javascript framework to create unobtrusive, accessible DOM scripting effects. The article will explore what constitutes best practices with regard to Javascript and, furthermore, why jQuery is a good choice of a framework to implement best practices.
1. Why jQuery?
jQuery is ideal because it can create impressive animations and interactions. jQuery is simple to understand and easy to use, which means the learning curve is small, while the possibilities are (almost) infinite.
Javascript and Best Practices
Javascript has long been the subject of many heated debates about whether it is possible to use it while still adhering to best practices regarding accessibility and standards compliance.
The answer to this question is still unresolved, however, the emergence of Javascript frameworks like jQuery has provided the necessary tools to create beautiful websites without having to worry (as much) about accessibility issues.
Obviously there are cases where a Javascript solution is not the best option. The rule of thumb here is: use DOM scripting to enhance functionality, not create it.
Unobtrusive DOM Scripting
While the term “DOM scripting” really just refers to the use of scripts (in this case, Javascripts) to access the Document Object Model, it has widely become accepted as a way of describing what should really be called “unobtrusive DOM scripting”—basically, the art of adding Javascript to your page in such a way that if there were NO Javascript, the page would still work (or at least degrade gracefully). In the website world, our DOM scripting is done using Javascript.
The Bottom Line: Accessible, Degradable Content
The aim of any web producer, designer or developer is to create content that is accessible to the widest range of audience. However, this has to be carefully balanced with design, interactivity and beauty. Using the theories set out in this article, designers, developers and web producers will have the knowledge and understanding to use jQuery for DOM scripting in an accessible and degradable way; maintaining content that is beautiful, functional AND accessible.
2. Unobtrusive DOM Scripting?
In an ideal world, websites would have dynamic functionality AND effects that degrade well. What does this mean? It would mean finding a way to include, say, a snazzy Javascript Web 2.0 animated sliding news ticker widget in a web page, while still ensuring that it fails gracefully if a visitor’s browser can’t (or won’t) run Javascripts.
The theory behind this technique is quite simple: the ultimate aim is to use Javascript for non-invasive, “behavioural” elements of the page. Javascript is used to add or enhance interactivity and effects. The primary rules for DOM scripting follow.
Rule #1: Separate Javascript Functionality
Separate Javascript functionality into a “behavioural layer,” so that it is separate from and independent of (X)HTML and CSS. (X)HTML is the markup, CSS the presentation and Javascript the behavioural layer. This means storing ALL Javascript code in external script files and building pages that do not rely on Javascript to be usable.
For a demonstration, check out the following code snippets:
Bad markup:
Never include Javascript events as inline attributes. This practice should be completely wiped from your mind.
<a onclick="doSomething()" href="#">Click!</a>
Good markup:
All Javascript behaviours should be included in external script files and linked to the document with a <script> tag in the head of the page. So, the anchor tag would appear like this:
<a href="backuplink.html" class="doSomething">Click!</a>
And the Javascript inside the myscript.js file would contain something like this:
... $('a.doSomething').click(function(){ // Do something here! alert('You did something, woo hoo!'); }); ...
The .click() method in jQuery allows us to easily attach a click event to the result(s) of our selector. So the code will select all of the <a> tags of class “doSomething” and attach a click event that will call the function. In practice, this
In Rule #2 there is a further demonstration of how a similar end can be achieved without inline Javascript code.
Rule #2: NEVER Depend on Javascript
To be truly unobtrusive, a developer should never rely on Javascript support to deliver content or information. It’s fine to use Javascript to enhance the information, make it prettier, or more interactive—but never assume the user’s browser will have Javascript enabled. This rule of thumb can in fact be applied to any third-party technology, such as Flash or Java. If it’s not built into every web browser (and always enabled), then be sure that the page is still completely accessible and usable without it.
Bad markup:
The following snippet shows Javascript that might be used to display a “Good morning” (or “afternoon”) message on a site, depending on the time of day. (Obviously this is a rudimentary example and would in fact probably be achieved in some server-side scripting language).
<script language="javascript"> var now = new Date(); if(now.getHours() < 12) document.write('Good Morning!'); else document.write('Good Afternoon!'); </script>
This inline script is bad because if the target browser has Javascript disabled, NOTHING will be rendered, leaving a gap in the page. This is NOT graceful degradation. The non-Javascript user is missing out on our welcome message.
Good markup:
A semantically correct and accessible way to implement this would require much simpler and more readable (X)HTML, like:
<p title="Good Day Message">Good Morning!</p>
By including the “title” attribute, this paragraph can be selected in jQuery using a selector (selectors are explained later in this article) like the one in the following Javascript snippet:
var now = new Date(); if(now.getHours() >= 12) { var goodDay = $('p[title="Good Day Message"]'); goodDay.text('Good Afternoon!'); }
The beauty here is that all the Javascript lives in an external script file and the page is rendered as standard (X)HTML, which means that if the Javascript isn’t run, the page is still 100% semantically pure (X)HTML—no Javascript cruft. The only problem would be that in the afternoon, the page would still say “Good morning.” However, this can be seen as an acceptable degradation.
Rule #3: Semantic and Accessible Markup Comes First
It is very important that the (X)HTML markup is semantically structured. (While it is outside the scope of this article to explain why, see the links below for further reading on semantic markup.) The general rule here is that if the page’s markup is semantically structured, it should follow that it is also accessible to a wide range of devices. This is not always true, though, but it is a good rule of thumb to get one started.
Semantic markup is important to unobtrusive DOM scripting because it shapes the path the developer will take to create the DOM scripted effect. The FIRST step in building any jQuery-enhanced widget into a page is to write the markup and make sure that the markup is semantic. Once this is achieved, the developer can then use jQuery to interact with the semantically correct markup (leaving an (X)HTML document that is clean and readable, and separating the behavioural layer).
Terrible markup:
The following snippet shows a typical list of items and descriptions in a typical (and terribly UNsemantic) way.
<table> <tr> <td onclick="doSomething();">First Option</td> <td>First option description</td> </tr> <tr> <td onclick="doSomething();">Second Option</td> <td>Second option description</td> </tr> </table>
Bad markup:
The following snippet shows a typical list of items and descriptions in a more semantic way. However, the inline Javascript is far from perfect.
<dl> <dt onclick="doSomething();">First Option</dt> <dd>First option description</dd> <dt onclick="doSomething();">Second Option</dt> <dd>Second option description</dd> </dl>
Good markup:
This snippet shows how the above list should be marked up. Any interaction with Javascript would be attached at DOM load using jQuery, effectively removing all behavioural markup from the rendered (X)HTML.
<dl id="OptionList"> <dt>First Option</dt> <dd>First option description</dd> <dt>Second Option</dt> <dd>Second option description</dd> </dl>
The <id> of “OptionList” will enable us to target this particular definition list in jQuery using a selector—more on this later.
3. Understanding jQuery for Unobtrusive DOM Scripting
This section will explore three priceless tips and tricks for using jQuery to implement best practices and accessible effects.
Understanding Selectors: the Backbone of jQuery
The first step to unobtrusive DOM scripting (at least in jQuery and Prototype) is using selectors. Selectors can (amazingly) select an element out of the DOM tree so that it can be manipulated in some way.
If you’re familiar with CSS then you’ll understand selectors in jQuery; they’re almost the same thing and use almost the same syntax. jQuery provides a special utility function to select elements. It is called $.
A set of very simple examples of jQuery selectors:
$(document); // Activate jQuery for object $('#mydiv') // Element with ID "mydiv" $('p.first') // P tags with class first. $('p[title="Hello"]') // P tags with title "Hello" $('p[title^="H"]') // P tags title starting with H
So, as the Javascript comments suggest:
- $(document);
The first option will apply the jQuery library methods to a DOM object (in this case, the document object). - $(’#mydiv’)
The second option will select every <div> that has the <id> attribute set to “mydiv”. - $(’p.first’)
The third option will select all of the <p> tags with the class of “first”. - $(’p[title="Hello"]‘)
This option will select from the page all <p> tags that have a title of “Hello”. Techniques like this enable the use of much more semantically correct (X)HTML markup, while still facilitating the DOM scripting required to create complex interactions. - $(’p[title^="H"]‘)
This enables the selection of all of the <p> tags on the page that have a title that starts with the letter H.
These examples barely scratch the surface.
Almost anything you can do in CSS3 will work in jQuery, plus many more complicated selectors. The complete list of selectors is well documented on the jQuery Selectors documentation page. If you’re feeling super-geeky, you could also read the CSS3 selector specification from the W3C.
Get ready.
$(document).ready()
Traditionally Javascript events were attached to a document using an “onload” attribute in the <body> tag of the page. Forget this practice. Wipe it from your mind.
jQuery provides us with a special utility on the document object, called “ready”, allowing us to execute code ONLY after the DOM has completely finished loading. This is the key to unobtrusive DOM scripting, as it allows us to completely separate our Javascript code from our markup. Using $(document).ready()
, we can queue up a series of events and have them execute after the DOM is initialized.
This means that we can create entire effects for our pages without changing the markup for the elements in question.
Hello World! Why $(document).ready() is SO cool
To demonstrate the beauty of this functionality, let’s recreate the standard introduction to Javascript: a “Hello World” alert box.
The following markup shows how we might have run a “Hello World” alert without jQuery:
Bad markup:
<script language="javascript"> alert('Hello World'); </script>
Good markup:
Using this functionality in jQuery is simple. The following code snippet demonstrates how we might call the age-old “Hello World” alert box after our document has loaded. The true beauty of this markup is that it lives in an external Javascript file. There is NO impact on the (X)HTML page.
$(document).ready(function() { alert('Hello World'); });
How it works
The $(document).ready() function takes a function as its argument. (In this case, an anonymous function is created inline—a technique that is used throughout the jQuery documentation.) The function passed to $(document).ready() is called after the DOM has finished loading and executes the code inside the function, in this case, calling the alert.
Dynamic CSS Rule Creation
One problem with many DOM scripting effects is that they often require us to hide elements of the document from view. This hiding is usually achieved through CSS. However, this is less than desirable. If a user’s browser does not support Javascript (or has Javascript disabled), yet does support CSS, then the elements that we hide in CSS will never be visible, since our Javascript interactions will not have run.
The solution to this comes in the form of a plugin for jQuery called cssRule, which allows us to use Javascript to easily add CSS rules to the style sheet of the document. This means we can hide elements of the page using CSS—however the CSS is ONLY executed IF Javascript is running.
Bad markup:
HTML: <h2>This is a heading</h2> <p class="hide-me-first"> This is some information about the heading. </p> CSS: p.hide-me-first { display: none; }
Assuming that a paragraph with the class of “hide-me-first” is going to first be hidden by CSS and then be displayed by a Javascript after some future user interaction, if the Javascript never runs the content will never be visible.
Good markup:
HTML: <h2>This is a heading</h2> <p class="hide-me-first"> This is some information about the heading. </p> jQuery Javascript: $(document).ready(function{ jQuery.cssRule("p.hide-me-first", "display", "none"); });
Using a $(document).ready() Javascript here to hide the paragraph element means that if Javascript is disabled, the paragraphs won’t ever be hidden—so the content is still accessible. This is the key reason for runtime, Javascript-based, dynamic CSS rule creation.
4. Conclusion
jQuery is an extremely powerful library that provides all the tools necessary to create beautiful interactions and animations in web pages, while empowering the developer to do so in an accessible and degradable manner.
This article has covered:
- Why unobtrusive DOM scripting is so important for accessibility,
- Why jQuery is the natural choice to implement unobtrusive DOM scripting effects,
- How jQuery selectors work,
- How to implement unobtrusive CSS rules in jQuery.
5. Further Reading
Further Reading: jQuery and JavaScript Practices
- jQuery Web Site: How jQuery Works and Tutorials
John Resig + Other Contributors
One of jQuery’s true strengths is the documentation provided by John Resig and his team. - 51 Best jQuery Tutorials and Examples
- Easy As Pie: Unobtrusive JavaScript
- Seven Rules of Unobtrusive JavaScript
- Learning jQuery
- Visual jQuery
- jQuery Tutorials For Designers
- jQuery For Designers
jQuery for Designers: learn how easy it is to apply web interaction using jQuery. - 15 Days Of jQuery
jQuery tutorials and example code that takes you from zero to hero in no time flat. - 15 Resources To Get You Started With jQuery From Scratch
- The Seven Rules Of Pragmatic Progressive Enhancement
- The Behaviour Layer Slides
Jeremy Keith
Great slide notes giving a quick rundown on unobtrusive Javascripting. - A List Apart: Behavioral Separation
Jeremy Keith
A more in-depth explanation of the idea of separating Javascript into an unobtrusive “behavioural” layer. - Unobtrusive JavaScript with jQuery
Simon Willison
A great set of slides about using jQuery unobtrusively. Also, finishes with a wonderful summary of jQuery methods and usage.
Further Reading: Semantic Markup
- Wikipedia: Definition of Semantics
It’s worth understanding the idea of semantics in general prior to trying to wrap one’s head around the concept of semantic markup. - Who cares about semantic markup?
Dave Shea
Dave Shea explores the benefits of semantic markup and - Standards don’t necessarily have anything to do with being semantically correct
Jason Kottke
Kottke discusses the differences between standards compliance and semantic markup. - CSS3 selector specification
W3C
The complete specification for CSS3 selectors (most of which work perfectly in jQuery selectors also). This is great reading for anyone who likes to keep up to date with best practices and standards compliance.
About the author
Alex Holt is a professional interactive designer and web developer who has worked successfully for a variety of clients in Australia, UK, USA and most recently Spain. His blog can be found at: soyrex.com, where he writes sporadically about a wide range of design and development topics (as well as the occasional off-topic rant).
发表评论
-
jQuery插件---兼容IE6的固定悬浮Postion:Fixed
2011-02-19 08:04 6214制作一个兼容IE6中的Postion:Fixed固定悬浮效果, ... -
JQuery读书笔记--Ajax调用
2009-09-24 05:31 1386Jquery中Ajax调用 $.ajax({ ... -
JQuery读书笔记--常用工具
2009-09-22 07:42 1066http://code.google.com/p/jqu ... -
JQuery读书笔记--JQuery1.3的Dreamweaver cs4的扩展
2009-04-22 03:22 2914发现专门为Dw4的jquery1.3扩展。 下载地 ... -
JQuery读书笔记--透明圆角插件
2009-04-16 08:54 1263将透明圆角功能做成了插件。其实很简单。 -
JQuery实例----浮动login
2009-04-09 05:17 1947相当不错的浮动login,感觉css技巧多于js技巧。 -
JQuery读书笔记--10 Best jQuery Plugins - March 2009
2009-03-27 07:46 2105Ajax最新Jquery plugins的 ... -
JQuery读书笔记--Learning Jquery1.3
2009-03-25 08:15 1074The latest book of jquery 1.3. ... -
JaveScript读书笔记-----Js 的 OOP编程
2009-03-25 08:09 1917一本好书,系统地讲js oop的。早几年看到就好了。英文的哦 -
JQuery读书笔记--OOB Jquery class
2009-03-12 02:32 2382It's really exiting, Jquery can ... -
JQuery-flexgrid的新家
2009-03-03 04:27 2755Jquery flexgrid的原来网址好像一直进不去,据说是 ... -
JQuery读书笔记--JQuery库中的Type技巧总结-3
2009-02-26 09:20 16037.Options JQuery中大量的使用Options作 ... -
JQuery读书笔记--JQuery库中的Type技巧总结-2
2009-02-26 01:45 12664.boolean boolean只有二个值true ... -
JQuery读书笔记--JQuery库中的Type技巧总结-1
2009-02-24 08:18 2859Javascript中有自己的各种type以及伪类pseudo ... -
JQuery读书笔记---很全面的教程
2009-02-13 13:11 1178http://www.bennadel.com/resourc ... -
JQuery读书笔记--JQuery官方论坛
2009-01-29 04:24 1154终于出现了,JQuery正一步一步完善自己。虽然这个论坛个人感 ... -
JQuery读书笔记--JQuery的OOP编程模板
2009-01-29 04:21 2409// // create closure // (functi ... -
JQuery读书笔记--clientX, clientY,offsetX, offsetY的区别
2009-01-28 04:06 4666Html中定位是非常重要的,否则再好的东西不能在它应该在的地方 ... -
JQuery Sample--改写后的lessmore
2009-01-21 09:47 1277js (function($) { // public ... -
JQuery读书笔记--PLUGIN code模板
2009-01-21 06:49 1341自己总结的PLUGIN code模板 /** * @a ...
相关推荐
jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-ui-1.8.16jquery-...
文件列表中的"jquery-1.4.2.js"和"jquery-1.4.2.min.js"分别是未压缩和压缩版的jQuery 1.4.2,是jQuery UI运行的基础。"jquery-1.4.2-vsdoc.js"是一个用于Visual Studio的文档文件,为开发者提供IDE内的API提示。 ...
`jquery-migrate-1.2.1.js` 文件是jQuery的一个辅助工具,它主要用于帮助开发者解决在升级到较新版本的jQuery时可能遇到的向后兼容性问题。这个插件的主要目的是为了警告开发者那些在新版本中已经被废弃或者更改的...
在本篇文章中,我们将深入探讨其自定义版本 `jquery-ui-1.8.18.custom.min.js` 和相关的 CSS 文件,以理解它们如何协同工作,为网页带来强大的功能和美观的界面。 首先,`jquery-ui-1.8.18.custom.min.js` 是 ...
这个压缩包包含两个关键文件:`jquery-ui-1.8.16.custom.min.js` 和 `jquery-ui-1.8.16.custom.css`,这些都是jQuery UI的特定版本,即1.8.16。这个版本在当时是一个广泛使用的稳定版本,提供了丰富的功能和组件。 ...
<script src="./public/js/jquery-ui-1.10.3.min.js"> <script src="./public/js/jquery.datepicker-zh-CN.js"></script> <link href="./public/css/jqueryui/jquery-ui-1.10.3.min.css" rel="stylesheet"> $( "#...
6. **压缩和非压缩版本**:提供的 `jquery.editable-select.js` 和 `jquery.editable-select.min.js` 分别是未压缩和压缩后的版本。在开发阶段,可以使用未压缩版方便调试,而在生产环境中,压缩版可以减少文件大小...
jquery-ui-日期框扩展成时间框 jquery-ui时间框 基于别人的代码进行修改 jquery-ui-1.8.16.custom.css文件末尾加入以下代码 .ui-timepicker-div .ui-widget-header{ margin-bottom: 8px; } .ui-timepicker-div dl{ ...
jquery-easyui-EDT-1.5.2-build1 jquery-easyui-EDT-1.5.2-build1
jQuery版本迁移辅助插件,如果您使用的低版本jQuery改为高版本后出现错误,可以试试这个插件。用来检测和恢复在jQuery1.9版本中已删除或已过时的API。jquery-migrate-1.2.1.js,jquery-migrate-1.2.1.min.js
压缩包内包含jquery-1.6.4.js jquery-1.6.4.min.js jquery-1.6.4-vsdoc.js 。 【推荐用法】 1、将jquery-1.6.4-vsdoc.js与jquery-1.6.4.js放在同一目录,然后在vs中添加对jquery-1.6.4.js的引用即可; 2、切记:...
最新jquery-ui-1.11.2日期控件,官网下载内涵图片和自己添加的中文辅助jquery-ui-timepicker-zh-CN.js,经过本人测试绝对可以用,不知道怎么用的百度上找个例子即可,需要导入的包 ${ctx}/plugins/jquery-ui-1.11.2/...
在生产环境中,使用最小化版本的JavaScript文件是最佳实践,因为它减少了网络传输的数据量,提高了用户体验。 3. **jQuery UI 1.9.2**: 这个版本号代表了jQuery UI的特定发布版本。1.9.2是jQuery UI历史上的一个...
这个小型的JavaScript文件(jquery-migrate-1.2.1.min.js)包含了必要的代码,用于检测和修复那些在新版本中已被移除或改变的功能。 1. **API修复**:在jQuery 1.9及以后的版本中,一些过时的API被废弃,如`.live()...
最佳实践是逐步升级和修改代码,以适应最新版本的jQuery,因为旧的API和特性可能有安全风险,或者效率较低。使用jQuery Migrate的目的是为了有一个平滑的过渡期,而不是永久依赖。 总的来说,jQuery Migrate 3.0.0...
<script src="path/to/jquery-migrate-3.0.1.js"> ``` 这里的`path/to`应该替换为实际的文件路径。 **四、迁移策略** 使用jQuery Migrate并不是长久之计,它只是一种过渡手段。开发者应根据控制台的警告信息,...
jquery-ui-1.10.3.min.js
jquery.json-2.3.min.js和jquery.json-2.3.js jQuery为开发插件提拱了两个方法,分别是:jQuery.extend(object); 为扩展jQuery类本身 jQuery.fn.extend(object);给jQuery对象添加方法。
jquery-ui-1.10.3.js 版本 1积分下载 jquery-ui-1.10.3.js 版本 1积分下载 jquery-ui-1.10.3.js 版本 1积分下载