jQuery setTimeout傳遞字串參數報錯的解決方案

來源:互聯網
上載者:User

當你打算調用一些jQuery代碼顯示隱藏的一個元素,並調用setTimeout()在一段延時之後設定其HTML的內容:

整個頁面的代碼是這樣的.
複製代碼 代碼如下:
<span style="font-size:18px;"><html>
<head>
<title></title>
</head>
<body>
<a href="#" id='heihei' onclick="showNext('I am veinei ')">show next</a>
<a href="#" id="log" style="display:none" >yes,I am the next </a>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function showNext(text){
setTimeout("$('#log').show().text(text)",1000);
}
</script>
</body>
</html>
</span>

.show()確實調用成功了.但是.text()調用失敗了.console顯示 text未定義.

對於這個問題,我確實沒有找到更好的答案...我想是不是jQuery對這個傳入setTimeout()函數的內容做了修改導致變數失效.

我緊接著做了下一個實驗.
複製代碼 代碼如下:
<span style="font-size:18px;"><html>
<head>
<title></title>
</head>
<body>
<a href="#" id='heihei' onclick="showNext('I am veinei ')">show next</a>
<a href="#" id="log" style="display:none" >yes,I am the next </a>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function showNext(text){
setTimeout("alert(text)",1000);
}
</script>
</body>
</html>
</span>

我要看看是不是確實是jQuery出了問題.得到的是同樣的錯誤.

後來找了本書看了看.發現了問題的所在.

setTimeout() 接受一個字串參數時,它執行於全域範圍,也就是說,它位於任何函數之外.最簡單的修複手段就是使用一個局部函數(匿名函數)來解決這個問題.
複製代碼 代碼如下:
<span style="font-size:18px;"><html>
<head>
<title></title>
</head>
<body>
<a href="#" id='heihei' onclick="showNext('I am veinei ')">show next</a>
<a href="#" id="log" style="display:none" >yes,I am the next </a>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function showNext(text){
setTimeout(function(){$('#log').show().text(text);},1000);
}
</script>
</body>
</html>
</span>

成功解決這個問題.

聯繫我們

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