点击后转到随机页面

时间:2014-01-18 22:35:41

标签: javascript jquery jquery-mobile

我有一个简单的移动网站,我想在按钮点击上显示随机内容。我正在使用一个简单的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移动链接之后。

在chrome的javascript控制台中我得到了:

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

有没有人有任何想法?

1 个答案:

答案 0 :(得分: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