从jquery发送一个变量给javascript函数

Send a variable to javascript function from jquery

本文关键字:变量 一个 javascript 函数 jquery      更新时间:2023-09-26

我有一个成功调用javascript函数的jquery mouseover事件

$(document).ready(function() {
$('.nw').mouseover(run_nw);
});
function run_nw() {
...
}

然而,当我试图传递参数时,js失败了。

$(document).ready(function() {
$('.nw').mouseover(run_nw(1));
});
var a;
function run_nw(a) {
...
}

试着看了看SO和jQ文档,但我仍然被难住了。我想这是一个简单的格式问题。

感谢

(如果有帮助,这里是完整的代码)

    <script>
    var $ = jQuery.noConflict();
    var incr = 650;
        function run_nw() {
            //move x and y
            var topAdjust = -incr;
            var leftAdjust = -incr;
            var top = parseInt($(this).css('top'))+topAdjust;
            var left = parseInt($(this).parent().css('left'))+leftAdjust;
            //rotate
            var randomnumber = Math.floor(Math.random()*11);
            var rotate = -randomnumber*10;
            $(this).animate({
                top:top,
                left:left,
                'rotate':rotate
            }, 700, 'swing');
        }
        $(document).ready(function() {
            $('.nw').mouseover(run_nw);
        });
    </script>

将函数调用封装在一个匿名函数中:

$('.nw').mouseover(function() {
    run_nw(1);
});

当前的方法是执行函数并将结果作为回调给mouseover

你当前的代码的问题是,在事件处理程序函数,this不指你所期望的(它指的是窗口,因为你正在调用函数从一个匿名回调到mouseover - this内的匿名回调是你想要的)。

因此,你需要将this传递给函数并将任何对this的引用更改为你选择的参数名称:

$('.nw').mouseover(function() {
    run_nw(1, this);
});
function run_nw(a, elem) {
    //Now `elem` is what you expected `this` to be
}