1. 程式人生 > >javascript 前端學習經驗總結

javascript 前端學習經驗總結

javascript

HTML編碼規範-屬性次序

HTML 屬性應當按照以下給出的順序依次排列,確保程式碼的易讀性。

    class
    id, name
    data-*
    src, for, type, href
    title, alt
    aria-*, role

console.debug

  • 遮蔽測試程式碼:
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd"
, "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}
  • 禁止所有表格提交出去
<script>
$(document).ready(function(){
  $("form").submit(function(e){
   e.preventDefault;
  });
});
</script
>

jquery selector

  • selector

    在jQuery中去選擇一個元素,不論元素存在與否,選擇器都是一個物件型別,其typeof 為object;若元素不存在,其length屬性為0
    若是陣列,遍歷其中每一個元素,再做判斷。選擇器選擇的某個元素是否存在,且唯一 若是物件,length===1,若需判斷內容非空;
    若是字串,value()應該不是空的字串,$().value() length!===0;


聯合選擇器
$(".panel.panel-info")//無空格表示子類選擇,在.panel下找.panel-info
$(".panel. panel-info")
//屬於css聯合選擇器。選擇.panel類元素下的所有.panel-info類子元素,聯合選擇器如下所示
聯合選擇器 示例 解釋
element,element div,p 選擇所有<div>元素和<p>元素
element element div p 選擇<div>元素內的所有<p>元素
element>element div>p 選擇所有父級是 <div> 元素的<p>元素
element+element div+p 選擇所有緊接著<div>元素之後的<p>元素
* focus blur 那些元素可以獲得焦點呢?
  • a elements that have an href attribute
  • link elements that have an href attribute
  • button elements that are not disabled
  • input elements whose type attribute are not in the Hidden state and that are not disabled
  • select elements that are not disabled
  • textarea elements that are not disabled
  • command elements that do not have a disabled attribute
  • Elements with a draggable attribute set, if that would enable the user agent to allow the user to begin a drag operations for those elements without the use of a pointing device
    Each shape that is generated for an area element
除上面以外的元素(比如:div,p)一般都無法直接獲得焦點,那如何處理呢? 給元素新增 tabindex 屬性,對使無法直接獲得焦點的元素獲得焦點的最佳實踐就是:給元素新增 `tabindex = -1`

The tabindex content attribute specifies whether the element is focusable, whether it can be reached using sequential focus navigation, and the relative order of the element for the purposes of sequential focus navigation.
If the value is a negative integer: The user agent must allow the element to be focused, but should not allow the element to be reached using sequential focus navigation.

  • each() 方法為每個匹配元素規定要執行的函式 $(selector).each(function(index,element))
    example:
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("li").each(function(){
      $(this).click(function(){
          alert($(this).text());
      })
    });
  });
});
</script>

對選中的元素中的每一個元素繫結事件時,不能用如下方式的迴圈語句,因為當文件載入完場後,i的值已經等於x.length;當單擊事件觸發後,i的值為x.length,因此,x.eq(i).length===0,因此,x.eq(i)實際上成為一個空元素,其text()方法返回結果自然為空。

$(document).ready(function(){
  $("button").click(function(){
    x=$("li");
      for (i=0;i<x.length;i++)
      {
        x.eq(i).click(function (){
             alert(x.eq(i).text());
             console.error(x.eq(i).length);
        });
      }
  });
});
</script>

form

  • form input type="upload"

    包含檔案上傳的表單應包括以下屬性:
    enctype="multipart/form-data"
    target="upload_target"


表單中enctype=”multipart/form-data”的意思,是設定表單的MIME編碼。預設情況,這個編碼格式是application/x-www-form-urlencoded,不能用於檔案上傳;只有使用了multipart/form-data,才能完整的傳遞檔案資料,進行下面的操作.
enctype=”multipart/form-data”是上傳二進位制資料; form裡面的input的值以2進位制的方式傳過去。

target 屬性規定一個名稱或一個關鍵詞,指示在何處開啟 action URL,即在何處顯示提交表單後接收到的響應。
格式如下:

<form target="_blank|_self|_parent|_top|framename">

notes: 在 HTML5 中,不再支援 frame 和 frameset,所以 _parent、_top 和 framename 值大多用於 iframe。

  • select checkbox radio
    採用checkbox物件的isChecked()方法確定checkbox是否被選中
    jQuery( ":checked" ) The :checked selector works for checkboxes, radio buttons, and options of select elements.
    To retrieve only the selected options of select elements, use the :selected selector.
<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />
Instead, drop the ID, and then select them by name, or by a containing element:
<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>
And now the jQuery:
var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;
(.is())

Description: Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

is(":checked")
  • form submit event
    為form的submit事件新增驗證函式,而不是為物件新增

jquery ajax

  • convert json into javascript object
    JSON.parse(data)

  • 宣告一個變數但沒有賦值,此時這個變數的值為undefined. Undefined用作數字時型別表現為NaN, 用作布林時表現為false.

  • sort 方法返回一個元素已經進行了排序的 Array 物件。

Array.prototype.sort()

Syntax
arr.sort()
arr.sort(compareFunction)

f compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, “80” comes before “9” in Unicode order.

var scores = [1, 10, 21, 2]; 
scores.sort(); // [1, 10, 2, 21]
// Watch out that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.

To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array ascending (if it doesn’t contain Infinity and NaN):

function compareNumbers(a, b) {
  return a - b;
}
var cc=[
{ name: "a", age: 30},
{ name: "c", age: 24},
{ name: "b", age: 28},
{ name: "e", age: 18},
{ name: "d", age: 38}
].sort(function(obj1, obj2) {
return obj1.age - obj2.age;
});
for(var i=0;i<cc.length;i++){
alert(cc[i]['age']); //依次顯示 18,24,28,30,38
}