开发者

Pass variables to a pre-defined jQuery function

开发者 https://www.devze.com 2022-12-14 23:52 出处:网络
Ok, so I have: function myfunc(foo,bar) { $(\'#div\' + foo).hide(); $(\'#div\' + bar).show(); return false;

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

精彩评论

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