开发者

Pass variables to a pre-defined jQuery function

Ok, so I have:

function myfunc(foo,bar) {
    $('#div' + foo).hide();
    $('#div' + bar).show();
    return false;
}

Then I have:

function myOtherFunc() {
// define vars foo and bar
    myfunc(foo,bar);
}
var timerId = setInterval(myOtherFunc, 5000); // run myOtherFunc every 5 seconds.

which works fine开发者_StackOverflow. But the I have:

$('#myLink').click(function(){
// define vars 'foo' and 'bar'
myfunc(foo,bar);
return false;
});

Which doesn't work at all... What am I doing wrong?


Since bb will be of type String, foo will be a string, and Javascript will cast the value 1 into a string when you perform the + operator. You can simply change this to;

var aa = $('.mydiv').attr('id'); // get current div's ID
var bb = aa.substring(6,7); // extract the number of the id, i.e. div1 will return '1'
var foo = bb;
var bar = parseInt(foo) + 1;


I believe it has something to do with the JavaScript handles type conversion. try parsing foo into an int. parseInt(foo, 10)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜