代碼<!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對象。