jquery如何把參數列嚴格轉換成數組

來源:互聯網
上載者:User

如果某參數的列只有一個參數,那麼each是失敗,請看下面的例子
Java代碼: 
<!DOCTYPE html> 
<html> 
<head> 
  <style> 
  p { margin: 8px; font-size:16px; } 
  .selected { color:red; } 
  .highlight { background:yellow; } 
  </style> 
  <script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 
  Hello 
 
  and 
 
  Goodbye 
 
script配合style一起實現在script修改樣式。 
<script> 
     var pp=3; 
     var a=[pp]; 
     alert(a); 
     $.each(pp,function(i,n){ 
      alert(i); 
     }); 
 </script> 
 
</body> 
</html> 

  結果是第一次alert是3,第二次沒有alert,說明pp不是數組,dom,jason等。
如何保證pp嚴格是數組呢,很簡單var a=[pp];這一句就行了,下面我們把each裡面的pp換成a,則結果是3,0,正確。注意這個中括弧把pp轉換成了數組。
Java代碼: 
<!DOCTYPE html> 
<html> 
<head> 
  <style> 
  p { margin: 8px; font-size:16px; } 
  .selected { color:red; } 
  .highlight { background:yellow; } 
  </style> 
  <script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 
  Hello 
  and  
  Goodbye 
 
script配合style一起實現在script修改樣式。 
<script> 
     var pp=3; 
     var a=[pp]; 
     alert(a); 
     $.each(a,function(i,n){ 
      alert(i); 
     }); 
 </script> 
 
</body> 
</html> 
  總結:當參數個數小於2時,要嚴格保證參數列為數組,嚴格每個都執行each操作,則需要對參數列長度是否大於2進行分別對待。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.