Tag: jquery

jQuery使用技巧

1、关于页面元素的引用
通过jquery的$()引用元素包括通过id、class、元素名以及元素的层级关系及dom或者xpath条件等方法,且返回的对象为jquery对象(集合对象),不能直接调用dom定义的方法。

2、jQuery对象与dom对象的转换
只有jquery对象才能使用jquery定义的方法。注意dom对象和jquery对象是有区别的,调用方法时要注意操作的是dom对象还是 jquery对象。
普通的dom对象一般可以通过$()转换成jquery对象。
如:$(document.getElementById(”msg”))则为jquery对象,可以使用jquery的方法。
由于jquery对象本身是一个集合。所以如果jquery对象要转换为dom对象则必须取出其中的某一项,一般可通过索引取出。
如:$(”#msg”)[0],$(”div”).eq(1)[0],$(”div”).get()[1],$(”td”)[5]这些都是dom对象,可以使用dom中的方法,但不能再使用Jquery的方法。
以下几种写法都是正确的:
$(”#msg”).html();
$(”#msg”)[0].innerHTML;
$(”#msg”).eq(0)[0].innerHTML;
$(”#msg”).get(0).innerHTML;

3、如何获取jQuery集合的某一项
对于获取的元素集合,获取其中的某一项(通过索引指定)可以使用eq或get(n)方法或者索引号获取,要注意,eq返回的是jquery对象,而 get(n)和索引返回的是dom元素对象。对于jquery对象只能使用jquery的方法,而dom对象只能使用dom的方法,如要获取第三个

元素的内容。有如下两种方法:
$(”div”).eq(2).html(); //调用jquery对象的方法
$(”div”).get(2).innerHTML; //调用dom的方法属性

4、同一函数实现set和get
Jquery中的很多方法都是如此,主要包括如下几个:
$(”#msg”).html(); //返回id为msg的元素节点的html内容。
$(”#msg”).html(”new content“);
//将“new content” 作为html串写入id为msg的元素节点内容中,页面显示粗体的new content

$(”#msg”).text(); //返回id为msg的元素节点的文本内容。
$(”#msg”).text(”new content“);
//将“new content” 作为普通文本串写入id为msg的元素节点内容中,页面显示new content

$(”#msg”).height(); //返回id为msg的元素的高度
$(”#msg”).height(”300″); //将id为msg的元素的高度设为300
$(”#msg”).width(); //返回id为msg的元素的宽度
$(”#msg”).width(”300″); //将id为msg的元素的宽度设为300

$(”input”).val(”); //返回表单输入框的value值
$(”input”).val(”test”); //将表单输入框的value值设为test

$(”#msg”).click(); //触发id为msg的元素的单击事件
$(”#msg”).click(fn); //为id为msg的元素单击事件添加函数
同样blur,focus,select,submit事件都可以有着两种调用方法

5、集合处理功能
对于jquery返回的集合内容无需我们自己循环遍历并对每个对象分别做处理,jquery已经为我们提供的很方便的方法进行集合的处理。
包括两种形式:
$(”p”).each(function(i){this.style.color=['#f00','#0f0','#00f'][ i ]})
//为索引分别为0,1,2的p元素分别设定不同的字体颜色。

$(”tr”).each(function(i){this.style.backgroundColor=['#ccc','#fff'][i%2]})
//实现表格的隔行换色效果

$(”p”).click(function(){alert($(this).html())})
//为每个p元素增加了click事件,单击某个p元素则弹出其内容

6、扩展我们需要的功能
$.extend({
min: function(a, b){return a < b?a:b; },
max: function(a, b){return a > b?a:b; }
}); //为jquery扩展了min,max两个方法
使用扩展的方法(通过“$.方法名”调用):
alert(”a=10,b=20,max=”+$.max(10,20)+”,min=”+$.min(10,20));

7、支持方法的连写
所谓连写,即可以对一个jquery对象连续调用各种不同的方法。
例如:
$(”p”).click(function(){alert($(this).html())})
.mouseover(function(){alert(’mouse over event’)})
.each(function(i){this.style.color=['#f00','#0f0','#00f'][ i ]});

8、操作元素的样式
主要包括以下几种方式:
$(”#msg”).css(”background”); //返回元素的背景颜色
$(”#msg”).css(”background”,”#ccc”) //设定元素背景为灰色
$(”#msg”).height(300); $(”#msg”).width(”200″); //设定宽高
$(”#msg”).css({ color: “red”, background: “blue” });//以名值对的形式设定样式
$(”#msg”).addClass(”select”); //为元素增加名称为select的class
$(”#msg”).removeClass(”select”); //删除元素名称为select的class
$(”#msg”).toggleClass(”select”); //如果存在(不存在)就删除(添加)名称为select的class

9、完善的事件处理功能
Jquery已经为我们提供了各种事件处理方法,我们无需在html元素上直接写事件,而可以直接为通过jquery获取的对象添加事件。
如:
$(”#msg”).click(function(){alert(”good”)}) //为元素添加了单击事件
$(”p”).click(function(i){this.style.color=['#f00','#0f0','#00f'][ i ]})
//为三个不同的p元素单击事件分别设定不同的处理
jQuery中几个自定义的事件:
(1)hover(fn1,fn2):一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。当鼠标移动到一个匹配的元素上面时,会触发指定的第一个函数。当鼠标移出这个元素时,会触发指定的第二个函数。
//当鼠标放在表格的某行上时将class置为over,离开时置为out。
$(”tr”).hover(function(){
$(this).addClass(”over”);
},
function(){
$(this).addClass(”out”);
});
(2)ready(fn):当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
$(document).ready(function(){alert(”Load Success”)})
//页面加载完毕提示“Load Success”,相当于onload事件。与$(fn)等价
(3)toggle(evenFn,oddFn): 每次点击时切换要调用的函数。如果点击了一个匹配的元素,则触发指定的第一个函数,当再次点击同一元素时,则触发指定的第二个函数。随后的每次点击都重复对这两个函数的轮番调用。
//每次点击时轮换添加和删除名为selected的class。
$(”p”).toggle(function(){
$(this).addClass(”selected”);
},function(){
$(this).removeClass(”selected”);
});
(4)trigger(eventtype): 在每一个匹配的元素上触发某类事件。
例如:
$(”p”).trigger(”click”); //触发所有p元素的click事件
(5)bind(eventtype,fn),unbind(eventtype): 事件的绑定与反绑定
从每一个匹配的元素中(添加)删除绑定的事件。
例如:
$(”p”).bind(”click”, function(){alert($(this).text());}); //为每个p元素添加单击事件
$(”p”).unbind(); //删除所有p元素上的所有事件
$(”p”).unbind(”click”) //删除所有p元素上的单击事件

10、几个实用特效功能
其中toggle()和slidetoggle()方法提供了状态切换功能。
如toggle()方法包括了hide()和show()方法。
slideToggle()方法包括了slideDown()和slideUp方法。

11、几个有用的jQuery方法
$.browser.浏览器类型:检测浏览器类型。有效参数:safari, opera, msie, mozilla。如检测是否ie:$.browser.isie,是ie浏览器则返回true。
$.each(obj, fn):通用的迭代函数。可用于近似地迭代对象和数组(代替循环)。

$.each( [0,1,2], function(i, n){ alert( “Item #” + i + “: ” + n ); });
等价于:
var tempArr=[0,1,2];
for(var i=0;i alert("Item #"+i+": "+tempArr[ i ]);
}
也可以处理json数据,如
$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); });
结果为:
Name:name, Value:John
Name:lang, Value:JS
$.extend(target,prop1,propN):用一个或多个其他对象来扩展一个对象,返回这个被扩展的对象。这是jquery实现的继承方式。
如:
$.extend(settings, options);
//合并settings和options,并将合并结果返回settings中,相当于options继承setting并将继承结果保存在 setting中。
var settings = $.extend({}, defaults, options);
//合并defaults和options,并将合并结果返回到setting中而不覆盖default内容。
可以有多个参数(合并多项并返回)
$.map(array, fn):数组映射。把一个数组中的项目(处理转换后)保存到到另一个新数组中,并返回生成的新数组。
如:
var tempArr=$.map( [0,1,2], function(i){ return i + 4; });
tempArr内容为:[4,5,6]
var tempArr=$.map( [0,1,2], function(i){ return i > 0 ? i + 1 : null; });
tempArr内容为:[2,3]
$.merge(arr1,arr2):合并两个数组并删除其中重复的项目。
如:$.merge( [0,1,2], [2,3,4] ) //返回[0,1,2,3,4]
$.trim(str):删除字符串两端的空白字符。
如:$.trim(” hello, how are you? “); //返回”hello,how are you? ”

12、解决自定义方法或其他类库与jQuery的冲突
很多时候我们自己定义了$(id)方法来获取一个元素,或者其他的一些js类库如prototype也都定义了$方法,如果同时把这些内容放在一起就会引起变量方法定义冲突,Jquery对此专门提供了方法用于解决此问题。
使用jquery中的jQuery.noConflict();方法即可把变量$的控制权让渡给第一个实现它的那个库或之前自定义的$方法。之后应用 Jquery的时候只要将所有的$换成jQuery即可,如原来引用对象方法$(”#msg”)改为jQuery(”#msg”)。
如:
jQuery.noConflict();
// 开始使用jQuery
jQuery(”div p”).hide();
// 使用其他库的 $()
$(”content”).style.display = ‘none’;
========================================================================================================
以上资料从网上转载而来,因同事需要提供给同事,现发在这里供大家共享。


24 JavaScript Best Practices for Beginners

1. Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

“If two operands are of the same type and value, then === produces true and !== produces false.” – JavaScript: The Good Parts

However, when working with == and !=, you’ll run into issues when working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.

2. Eval = Bad

For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”.

Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!

3. Don’t Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:

  • if(someVariableExists) ??
  • ???x?=?false??
  • if(someVariableExists)
       x = false

    However, consider this:

  • if(someVariableExists) ??
  • ???x?=?false??
  • ???anotherFunctionCall();??
  • if(someVariableExists)
       x = false
       anotherFunctionCall();

    One might think that the code above would be equivalent to:

  • if(someVariableExists)?{ ??
  • ???x?=?false; ??
  • ???anotherFunctionCall(); ??
  • }??
  • if(someVariableExists) {
       x = false;
       anotherFunctionCall();
    }

    Unfortunately, he’d be wrong. In reality, it means:

  • if(someVariableExists)?{ ??
  • ???x?=?false; ??
  • } ??
  • anotherFunctionCall();??
  • if(someVariableExists) {
       x = false;
    }
    anotherFunctionCall();

    As you’ll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

  • if(2?+?2?===?4)?return?‘nicely?done’;??
  • if(2 + 2 === 4) return 'nicely done';

    Always Consider the Future

    What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line – tread with caution when omitting.

    4. Utilize JS Lint

    JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.

    “JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.”
    - JSLint Documentation

    Before signing off on a script, run it through JSLint just to be sure that you haven’t made any mindless mistakes.

    5. Place Scripts at the Bottom of Your Page

    This tip has already been recommended in the previous article in this series. As it’s highly appropriate though, I’ll paste in the information.

    Place JS at bottom

    Remember — the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can’t continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

    If you have JS files whose only purpose is to add functionality — for example, after a button is clicked — go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

    Better

  • <p>And?now?you?know?my?favorite?kinds?of?corn.?</p>??
  • ?<script?type=“text/javascript”?src=“path/to/file.js”></script>??
  • ?<script?type=“text/javascript”?src=“path/to/anotherFile.js”></script>??
  • ?</body>??
  • ?</html>??
  • <p>And now you know my favorite kinds of corn. </p>
    <script type="text/javascript" src="path/to/file.js"></script>
    <script type="text/javascript" src="path/to/anotherFile.js"></script>
    </body>
    </html>

    6. Declare Variables Outside of the For Statement

    When executing lengthy “for” statements, don’t make the engine work any harder than it must. For example:

    Bad

  • for(var?i?=?0;?i?<?someArray.length;?i++)?{ ??
  • ???var?container?=?document.getElementById(‘container’); ??
  • ???container.innerHtml?+=?‘my?number:?’?+?i; ??
  • ???console.log(i); ??
  • }??
  • for(var i = 0; i < someArray.length; i++) {
       var container = document.getElementById('container');
       container.innerHtml += 'my number: ' + i;
       console.log(i);
    }

    Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the “container” element each time — highly inefficient!

    Better

  • var?container?=?document.getElementById(‘container’); ??
  • ?for(var?i?=?0,?len?=?someArray.length;?i?<?len;??i++)?{ ??
  • ???container.innerHtml?+=?‘my?number:?’?+?i; ??
  • ???console.log(i); ??
  • }??
  • var container = document.getElementById('container');
    for(var i = 0, len = someArray.length; i < len;  i++) {
       container.innerHtml += 'my number: ' + i;
       console.log(i);
    }

    Bonus points to the person who leaves a comment showing us how we can further improve the code block above.

    7. The Fastest Way to Build a String

    Don’t always reach for your handy-dandy “for” statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

  • var?arr?=?['item?1',?'item?2',?'item?3',?...]; ??
  • ?var?list?=?‘<ul><li>’?+?arr.join(‘</li><li>’)?+?‘</li></ul>’;??
  • var arr = ['item 1', 'item 2', 'item 3', ...];
    var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

    I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) – this is by far the fastest method!

    Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.
    - James Padolsey, james.padolsey.com

    8. Reduce Globals

    “By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.”
    - Douglas Crockford

  • var?name?=?‘Jeffrey’; ??
  • ?var?lastName?=?‘Way’; ??
  • ??
  • ?function?doSomething()?{…} ??
  • ??
  • console.log(name);?//?Jeffrey?–?or?window.name??
  • var name = 'Jeffrey';
    var lastName = 'Way';
    
    function doSomething() {...}
    
    console.log(name); // Jeffrey -- or window.name

    Better

  • var?DudeNameSpace?=?{ ??
  • ???name?:?‘Jeffrey’, ??
  • ???lastName?:?‘Way’, ??
  • ???doSomething?:?function()?{…} ??
  • } ??
  • console.log(DudeNameSpace.name);?//?Jeffrey??
  • var DudeNameSpace = {
       name : 'Jeffrey',
       lastName : 'Way',
       doSomething : function() {...}
    }
    console.log(DudeNameSpace.name); // Jeffrey

    Notice how we’ve “reduced our footprint” to just the ridiculously named “DudeNameSpace” object.

    9. Comment Your Code

    It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can’t easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

  • //?Cycle?through?array?and?echo?out?each?name.? ??
  • ?for(var?i?=?0,?len?=?array.length;?i?<?len;?i++)?{ ??
  • ???console.log(array[i]); ??
  • }??
  • // Cycle through array and echo out each name.
    for(var i = 0, len = array.length; i < len; i++) {
       console.log(array[i]);
    }

    10. Embrace Progressive Enhancement

    Always compensate for when JavaScript is disabled. It might be tempting to think, “The majority of my viewers have JavaScript enabled, so I won’t worry about it.” However, this would be a huge mistake.

    Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you’ve done so, begin to progressively enhance your layout!

    11. Don’t Pass a String to “SetInterval” or “SetTimeOut”

    Consider the following code:

  • setInterval( ??
  • ?“document.getElementById(’container’).innerHTML?+=?’My?new?number:?’?+?i”,?3000 ??
  • );??
  • setInterval(
    "document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
    );

    Not only is this code inefficient, but it also functions in the same way as the “eval” function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.

  • setInterval(someFunction,?3000);??
  • setInterval(someFunction, 3000);

    12. Don’t Use the “With” Statement

    At first glance, “With” statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects. For example…

  • with?(being.person.man.bodyparts)?{ ??
  • ???arms?=?true; ??
  • ???legs?=?true; ??
  • }??
  • with (being.person.man.bodyparts) {
       arms = true;
       legs = true;
    }

    – instead of –

  • being.person.man.bodyparts.arms?=?true; ??
  • being.person.man.bodyparts.legs=?true;??
  • being.person.man.bodyparts.arms = true;
    being.person.man.bodyparts.legs= true;

    Unfortunately, after some testing, it was found that they “behave very badly when setting new members.” Instead, you should use var.

  • var?o?=?being.person.man.bodyparts; ??
  • o.arms?=?true; ??
  • o.legs?=?true;??
  • var o = being.person.man.bodyparts;
    o.arms = true;
    o.legs = true;

    13. Use {} Instead of New Object()

    There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the “new” constructor, like so:

  • var?o?=?new?Object(); ??
  • o.name?=?‘Jeffrey’; ??
  • o.lastName?=?‘Way’; ??
  • o.someFunction?=?function()?{ ??
  • ???console.log(this.name); ??
  • }??
  • var o = new Object();
    o.name = 'Jeffrey';
    o.lastName = 'Way';
    o.someFunction = function() {
       console.log(this.name);
    }

    However, this method receives the “bad practice” stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

    Better

  • var?o?=?{ ??
  • ???name:?‘Jeffrey’, ??
  • ???lastName?=?‘Way’, ??
  • ???someFunction?:?function()?{ ??
  • ??????console.log(this.name); ??
  • ???} ??
  • };??
  • var o = {
       name: 'Jeffrey',
       lastName = 'Way',
       someFunction : function() {
          console.log(this.name);
       }
    };

    Note that if you simply want to create an empty object, {} will do the trick.

  • var?o?=?{};??
  • var o = {};

    “Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc.” – dyn-web.com

    14. Use [] Instead of New Array()

    The same applies for creating a new array.

    Okay

  • var?a?=?new?Array(); ??
  • a[0]?=?“Joe”; ??
  • a[1]?=?‘Plumber’;??
  • var a = new Array();
    a[0] = "Joe";
    a[1] = 'Plumber';

    Better

  • var?a?=?['Joe','Plumber'];??
  • var a = ['Joe','Plumber'];

    “A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object.” – Douglas Crockford

    15. Long List of Variables? Omit the “Var” Keyword and Use Commas Instead

  • var?someItem?=?’some?string’; ??
  • ?var?anotherItem?=?‘another?string’; ??
  • ?var?oneMoreItem?=?‘one?more?string’;??
  • var someItem = 'some string';
    var anotherItem = 'another string';
    var oneMoreItem = 'one more string';

    Better

  • var?someItem?=?’some?string’, ??
  • ????anotherItem?=?‘another?string’, ??
  • ????oneMoreItem?=?‘one?more?string’;??
  • var someItem = 'some string',
        anotherItem = 'another string',
        oneMoreItem = 'one more string';

    …Should be rather self-explanatory. I doubt there’s any real speed improvements here, but it cleans up your code a bit.

    17. Always, Always Use Semicolons

    Technically, most browsers will allow you to get away with omitting semi-colons.

  • var?someItem?=?’some?string’??
  • ?function?doSomething()?{ ??
  • ??return?’something’??
  • }??
  • var someItem = 'some string'
    function doSomething() {
      return 'something'
    }

    Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.

    Better

  • var?someItem?=?’some?string’; ??
  • ?function?doSomething()?{ ??
  • ??return?’something’; ??
  • }??
  • var someItem = 'some string';
    function doSomething() {
      return 'something';
    }

    18. “For in” Statements

    When looping through items in an object, you might find that you’ll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information

  • for(key?in?object)?{ ??
  • ???if(object.hasOwnProperty(key)?{ ??
  • ??????…then?do?something… ??
  • ???} ??
  • }??
  • for(key in object) {
       if(object.hasOwnProperty(key) {
          ...then do something...
       }
    }

    As referenced from JavaScript: The Good Parts, by Douglas Crockford.

    19. Use Firebug’s “Timer” Feature to Optimize Your Code

    Need a quick and easy way to determine how long an operation takes? Use Firebug’s “timer” feature to log the results.

  • function?TimeTracker(){ ??
  • ?console.time(“MyTimer”); ??
  • ?for(x=5000;?x?>?0;?x–){} ??
  • ?console.timeEnd(“MyTimer”); ??
  • }??
  • function TimeTracker(){
     console.time("MyTimer");
     for(x=5000; x > 0; x--){}
     console.timeEnd("MyTimer");
    }

    20. Read, Read, Read…

    While I’m a huge fan of web development blogs (like this one!), there really isn’t a substitute for a book when grabbing some lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here are some of my JavaScript favorites.

    Read them…multiple times. I still do!

    21. Self-Executing Functions

    Rather than calling a function, it’s quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.

  • (function?doSomething()?{ ??
  • ???return?{ ??
  • ??????name:?‘jeff’, ??
  • ??????lastName:?‘way’??
  • ???}; ??
  • })();??
  • (function doSomething() {
       return {
          name: 'jeff',
          lastName: 'way'
       };
    })();

    22. Raw JavaScript Can Always Be Quicker Than Using a Library

    JavaScript libraries, such as jQuery and Mootools, can save you an enormous amount of time when coding — especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly).

    jQuery’s “each” method is great for looping, but using a native “for” statement will always be an ounce quicker.

    23. Crockford’s JSON.Parse

    Although JavaScript 2 should have a built-in JSON parser, as of this writing, we still need to implement our own. Douglas Crockford, the creator of JSON, has already created a parser that you can use. It can be downloaded HERE.

    Simply by importing the script, you’ll gain access to a new JSON global object, which can then be used to parse your .json file.

  • var?response?=?JSON.parse(xhr.responseText); ??
  • ??
  • ?var?container?=?document.getElementById(‘container’); ??
  • ?for(var?i?=?0,?len?=?response.length;?i?<?len;?i++)?{ ??
  • ??container.innerHTML?+=?‘<LI>’?+?response[i].name?+?‘?:?’?+?response[i].email?+?‘</LI>’; ??
  • }??
  •  var response = JSON.parse(xhr.responseText);
    
     var container = document.getElementById('container');
     for(var i = 0, len = response.length; i < len; i++) {
       container.innerHTML += '
    
  • ' + response[i].name + ' : ' + response[i].email + ''; }
  • 24. Remove “Language”

    Years ago, it wasn’t uncommon to find the “language” attribute within script tags.

  • <script?type=“text/javascript”?language=“javascript”> ??
  • … ??
  • </script>??
  • <script type="text/javascript" language="javascript">
    ...
    </script>

    However, this attribute has long since been deprecated; so leave it out.


    八款JS框架介绍及比较

    八款JS框架介绍及比较

    Dojo

    ???????? Dojo 是目前最为强大的JS框架,它在自己的 Wiki 上给自己下了一个定义,Dojo 是一个用 JavaScript 编写的开源的DHTML工具箱。Dojo 很想做一个”大一统”的工具箱,不仅仅是浏览器层面的,野心还是很大的。Dojo 包括 Ajax、Browser、Event、Widget 等跨浏览器 API,包括了 JS 本身的语言扩展,以及各个方面的工具类库,和比较完善的 UI 组件库,也被广泛应用在很多项目中,他的 UI 组件的特点是通过给 HTML 标签增加 TAG 的方式进行扩展,而不是通过写 JS 来生成,Dojo 的 API 模仿 Java 类库的组织方式。用 Dojo 写 Web OS 可谓非常方便。Dojo 现在已经 4.0 了,Dojo 强大的地方在于界面和特效的封装,可以让开发者快速构建一些兼容标准的界面。
    优点:库相当完善,发展时间也比较长,功能强大,据说利用 Dojo 的 io.bind() 可以实现 comet 看见其功能强大非一般,得到 IBM 和 SUN 的支持。
    缺点:文件体积比较大,200多KB,初次下载相当慢,此外,Dojo 的类库使用显得不是那么易用,JS语法增强方面不如 Prototype

    Prototype

    ???????? 它是一个非常优雅的 JS 库,定义了 JS 的面向对象扩展,DOM 操作API,事件等等,以 Prototype 为核心,形成了一个外围的各种各样的 JS 扩展库,是相当有前途的 JS 底层框架,值得推荐,感觉也是现实中应用最广的库类(RoR 集成的 AJAX JS 库),之上还有 Scriptaculous 实现一些JS组件功能和效果。
    优点:基本底层,易学易用,甚至是其他一些js特效开发包的底层,体积算是最小的了。
    缺点:如果说缺点,可能就是功能是他的弱项

    dScriptaculous

    ????????? Scriptaculous 是基于prototype.js 框架的 JS 效果。包含了 6 个 js 文件,不同的文件对应不同的 js 效果,所以说,如果底层用 prototype 的话,做js效果用 Scriptaculous 那是再合适不过的了,连大名鼎鼎的 digg 都在用他,可见不一般
    优点:基于prototype 是最大的优点,由于使用 prototype 的广泛性,无疑对用户书锦上添花。
    缺点:刚刚兴起,需要时间的磨练

    Yui-ext

    ??????? 基于 Yahoo UI 的扩展包 yui-ext 是具有 CS 风格的 Web 用户界面组件,能实现复杂的 Layout 布局,界面效果可以和 backbase 媲美,而且使用纯 javascript 代码开发。真正的可编辑的表格 Edit Grid,支持 XML 和 Json 数据类型,直接可以迁入 Grid。许多组件实现了对数据源的支持,例如动态的布局,可编辑的表格控件,动态加载的 Tree 控件、动态拖拽效果等等。从 1.0 beta 版开始同 Jquery 合作,推出基于 jQuery 的 Ext 1.0,提供了更多有趣的功能。
    优点:结构化,类似于 java 的结构,清晰明了,底层用到了 Jquery 的一些函数,使整合使用有了选择,最重要的一点是界面太让让人震撼了。
    缺点:太过复杂,整个界面的构造过于复杂。

    Jquery

    ???????JQuery 是一款同 prototype 一样优秀 js 开发库类,特别是对 css 和 XPath 的支持,使我们写 js 变得更加方便!如果你不是个 js 高手又想写出优秀的 js 效果,那么 JQuery 可以帮你达到目的!并且简介的语法和高的效率一直是jQuery追求的目标。
    优点:注重简介和高效,js 效果有 yui-ext 的选择,因为 yui-ext 重用了很多 jQuery 的函数
    缺点:据说太嫩,历史不悠久。

    Mochikit

    ????????? MochiKit 自称为一个轻量级的 js 框架。MochiKit 主要受到 Python 和 Python 标准库提供的很多便利之处的启发,另外还缓解了浏览器版本之间的不一致性。其中的 MochiKit.DOM 尤其方便,能够以比原始 JavaScript 更友好的方式处理 DOM 对象。MochiKit.DOM 大部分都是针对 XHTML 文档定制的,如果与 MochiKit 和 Ajax 结合在一起,使用 XHTML 包装的微格式尤其方便。Mochikit 可以直接对字符串或者数字格式化输出,比较实用和方便。它还有自己的 js 代码解释器
    优点:MochiKit.DOM 这部分很实用,简介也是很突出的
    缺点:轻量级的缺点

    Mootools

    ???????? MooTools 是一个简洁,模块化,面向对象的 JavaScript 框架。它能够帮助你更快,更简单地编写可扩展和兼容性强的 JavaScript 代码。Mootools 跟 prototypejs 相类似,语法几乎一样。但它提供的功能要比 prototypejs 多,而且更强大。比如增加了动画特效、拖放操作等等。
    优点:可以定制自己所需要的功能,可以说是 prototypejs 的增强版。
    缺点:不大不小,具体应用具体分析。

    Moo.fx

    ???????? Moo.fx是 一个超级轻量级的 javascript 特效库(7k),能够与 prototype.js 或mootools 框架一起使用。它非常快、易于使用、跨浏览器、符合标准,提供控制和修改任何 HTML 元素的 CSS 属性,包括颜色。它内置检查器能够防止用户通过多次或疯狂点击来破坏效果。moo.fx整体采用模块化设计,所以可以在它的基础上开发你需要的任何特效。
    优点:小块头有大能耐
    缺点:这么小了,已经不错了


    Copyright © 1996-2010 V酷吧. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress