2014-01-18 46 views
0

我有一個簡單的移動網站,我想要在按鈕上單擊顯示隨機內容。我正在使用一段簡單的javascript/jquery。轉到隨機頁面點擊

<script type="text/javascript"> 
var randomlinks=[]; 
randomlinks[0]="_1" 
randomlinks[1]="_2" 
randomlinks[2]="_3" 
randomlinks[3]="_4" 
randomlinks[4]="_5" 
randomlinks[5]="_6" 
randomlinks[6]="_7" 
randomlinks[7]="_8" 
randomlinks[8]="_9" 
randomlinks[9]="_10" 

function randomlink(){ 
var idx = Math.floor(Math.random()*randomlinks.length); 

$.mobile.changePage('#' + randomlinks[idx], {transition:'pop'}); 
} 
</script> 

我打電話來使用功能:

<a href="javascript:randomlink()" id="nextComp" data-inline="true" data-theme="a" data-role="button" data-corners="false" data-icon="arrow-r" data-iconpos="right">Next Comp</a> 

我知道有調用函數的更好的方法,但這是另外一個問題。

該腳本是在jquery移動鏈接之後。

在從鍍鉻的JavaScript控制檯我得到:

Uncaught TypeError: Cannot call method 'changePage' of undefined forhim.php:681 
randomlink forhim.php:681 
(anonymous function) 

有沒有人有什麼想法?

+1

你是否包括了jQuery移動圖書館在頁面中?因爲那個錯誤是說'$ .mobile'是未定義的。既然不是說'$'沒有定義,你必須包含jQuery庫,但是你還需要包含jQuery Mobile庫。 –

+0

這是一個非常好的方式來激怒你的網站的訪問者 –

+1

@EdHeal這完全取決於這個網站的目的是什麼。 – Brad

回答

0

嘗試主頁上的JQM pageinit事件過程中,而不是通過在href綁定功能:

<a href="#" id="nextComp" data-inline="true" data-theme="a" data-role="button" data-corners="false" data-icon="arrow-r" data-iconpos="right">Next Comp</a> 

$(document).on("pageinit", "#page1", function(){ 
    $(document).on("click", "#nextComp", function(){ 
     randomlink(); 
    }); 
}); 

這裏是一個工作DEMO