jquery對象和原生JavaScript對象

來源:互聯網
上載者:User
代碼<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>自動換行</title>
<script src="../jQuery/jquery-1.3.1.js" type="text/ecmascript"></script>
<style type="text/css">
*{ margin:0; padding:0; border:0;}
.text{ width:500px; height:500px; margin:20px auto; background-color:#CCC; padding:10px;}
</style>
</head>

<body>
  <p id="text" class="text">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</p>
<script type="text/javascript">
 //jquery對象不能使用原生的JavaScript對象的方法
 //如果想使用原生JavaScript對象的方法,可以通過get()方法將jquery對象轉化為原生的JavaScript對象。
  function breakWords(maxLen,obj){
      var text=$(obj).text();   //jquery的text()方法返回的是原始的字串資料型別,所以可以使用原生的js方法。
      var temp="";
      while(text.length>maxLen){
          temp+=text.substr(0,maxLen)+"<br />";  //substr是原生JavaScript字串對象的方法
          text=text.substr(maxLen,text.length);
      };
      temp+=text;
      $(obj).html(temp);  //這裡不能使用innerHTML因為${obj}是jquery對象。另外jquery對象的html()和text()方法是不一樣的,這裡使用html()而不用text()
  }
  breakWords(50,"#text");
</script>
</body>
</html>

 

應用了jquery時,在使用過程中一定要區分當前的操作對象是jquery對象還是原生的JavaScript對象。jquery對象只能使用jquery中定義的方法和屬性,而不能使用原生的JavaScript對象的方法和屬性。JavaScript對象也是類似的。當然jquery對象可以通過get()方法轉化為JavaScript對象,也可以通過$來建立jquery對象。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.