我过去曾经使用过此代码
function getRand(){
return Math.round(Math.random()*(css.length-1));
}
var css = new Array(
'<link rel="stylesheet" type="text/css" href="css/1.css">',
'<link rel="stylesheet" type="text/css" href="css/2.css">',
'<link rel="stylesheet" type="text/css" href="css/3.css">'
);
rand = getRand();
document.write(css[rand]);
现在,有人告诉我将函数放在此事件处理程序中:
$(document).bind("projectLoadComplete", function(e, pid) {
// insert function here
});
有人可以解释一下我的代码的哪一部分去吗?谢谢。
最佳答案
我假设您是要在其中放置函数调用,而不是实际的函数定义。
function getRandCss(){
var css = ['<link rel="stylesheet" type="text/css" href="css/1.css">',
'<link rel="stylesheet" type="text/css" href="css/2.css">',
'<link rel="stylesheet" type="text/css" href="css/3.css">'];
return css[Math.round(Math.random()*(css.length-1))];
}
$(document).bind("projectLoadComplete", function(e, pid){
$('body').append( getRandCss() );
});
但是,如果您确实必须将所有内容放入其中
$(document).bind("projectLoadComplete", function(e, pid){
function getRandCss(){
var css = ['<link rel="stylesheet" type="text/css" href="css/1.css">',
'<link rel="stylesheet" type="text/css" href="css/2.css">',
'<link rel="stylesheet" type="text/css" href="css/3.css">'];
return css[Math.round(Math.random()*(css.length-1))];
}
$('body').append( getRandCss() );
});