国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

高效的jQuery代碼編寫技巧總結

2024-05-06 15:10:55
字體:
來源:轉載
供稿:網友

最近寫了很多的js,雖然效果都實現了,但是總感覺自己寫的js在性能上還能有很大的提升。本文我計劃總結一些網上找的和我本人的一些建議,來提升你的jQuery和javascript代碼。好的代碼會帶來速度的提升。快速渲染和響應意味著更好的用戶體驗。謹以此文來提醒自己。

其次在腦子里牢牢記住jQuery就是javascript。這意味著我們應該采取相同的編碼慣例,風格指南和最佳實踐。

當你準備使用jQuery,我強烈建議你遵循下面這些指南:

緩存變量

DOM遍歷是昂貴的,所以盡量將會重用的元素緩存。

// 糟糕h = $('#element').height();$('#element').css('height',h-20);// 建議$element = $('#element');h = $element.height();$element.css('height',h-20);

避免全局變量

jQuery與javascript一樣,一般來說,最好確保你的變量在函數作用域內。

// 糟糕$element = $('#element');h = $element.height();$element.css('height',h-20);// 建議var $element = $('#element');var h = $element.height();$element.css('height',h-20);

使用匈牙利命名法

在變量前加$前綴,便于識別出jQuery對象。

// 糟糕var first = $('#first');var second = $('#second');var value = $first.val();// 建議 - 在jQuery對象前加$前綴var $first = $('#first');var $second = $('#second'),var value = $first.val();

使用 Var 鏈(單 Var 模式)

將多條var語句合并為一條語句,我建議將未賦值的變量放到后面。

var $first = $('#first'), $second = $('#second'), value = $first.val(), k = 3, cookiestring = 'SOMECOOKIESPLEASE', i, j, myArray = {};

請使用'On'

在新版jQuery中,更短的 on(“click”) 用來取代類似 click() 這樣的函數。在之前的版本中 on() 就是 bind()。自從jQuery 1.7版本后,on() 附加事件處理程序的首選方法。然而,出于一致性考慮,你可以簡單的全部使用 on()方法。

// 糟糕$first.click(function(){ $first.css('border','1px solid red'); $first.css('color','blue');});$first.hover(function(){ $first.css('border','1px solid red');})// 建議$first.on('click',function(){ $first.css('border','1px solid red'); $first.css('color','blue');})$first.on('hover',function(){ $first.css('border','1px solid red');})

精簡javascript

一般來說,最好盡可能合并函數。

// 糟糕$first.click(function(){ $first.css('border','1px solid red'); $first.css('color','blue');});// 建議$first.on('click',function(){ $first.css({ 'border':'1px solid red', 'color':'blue' });});

鏈式操作

jQuery實現方法的鏈式操作是非常容易的。下面利用這一點。

// 糟糕$second.html(value);$second.on('click',function(){ alert('hello everybody');});$second.fadeIn('slow');$second.animate({height:'120px'},500);// 建議$second.html(value);$second.on('click',function(){ alert('hello everybody');}).fadeIn('slow').animate({height:'120px'},500);            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 崇阳县| 青州市| 丹江口市| 五峰| 蓝田县| 庆阳市| 天台县| 思茅市| 博客| 达拉特旗| 义马市| 衡阳市| 神农架林区| 满城县| 江口县| 宁海县| 甘德县| 米易县| 天长市| 恭城| 洛隆县| 旌德县| 通城县| 西充县| 桃园县| 灵丘县| 建阳市| 新宁县| 东莞市| 阿鲁科尔沁旗| 梧州市| 和平县| 闽侯县| 侯马市| 黔东| 桐庐县| 宜兰县| 西乌珠穆沁旗| 博白县| 会理县| 图木舒克市|