分配变量OnClick随机动作

Assigning variable OnClick random action

本文关键字:随机 OnClick 变量 分配      更新时间:2023-09-26
var Rand1 = Math.floor(Math.random()*3);
var Rand2 = Rand1;
while ( Rand2 == Rand1 ){
    var Rand2 = Math.floor(Math.random()*3);
}
var step1 = Rand1;
var step2 = Rand2;
function moveto(step1, step2) {
    var w = $(document).width();
    $('#full').animate({
        left: -(step1*w)
    },  {
    duration: 3000,
    });
}
//what element is this supposed to be?
class="img bg-img1" OnClick="moveto('1');">

我的问题是:我需要分配随机数字Rand1到OnClick="moveto('Rand1');我怎么做呢?

试着从你的内联按钮/元素中删除onclick: http://jsfiddle.net/GApnw/

function randomNumbers() {
    var Rand1 = Math.floor(Math.random() * 3);
    var Rand2 = Rand1;
    while (Rand2 == Rand1) {
        var Rand2 = Math.floor(Math.random() * 3);
    }
    return [Rand1, Rand2];
}
function moveto(step1, step2) {
    var w = $(document).width();
    $('#full').animate({
        left: -(step1 * w)
    }, {
        duration: 3000,
    });
    alert(step1 + " " + step2);
}
$(function(){
    $(".img").click(function(){
        var randomNum = randomNumbers();
        moveto(randomNum[0], randomNum[1]);
    });
});

或者在你的move中调用RandomNumbers,如果你没有在其他地方给出数字。

首先,我假设Rand1是在全局上下文中声明的,因为它看起来像是来自您问题中的代码。如果是这种情况,为什么需要将其传递给事件处理程序?无论如何,它都可以从事件处理程序函数访问:

var Rand1 = Math.floor(Math.random()*3);
function moveto() {
    //Rand1 is accessible here
}

其次,它似乎是使用jQuery在你的moveto函数,所以为什么不使用jQuery附加事件监听器,以及,而不是做内联:

$(".bg-img1").click(moveto);