请给我长标题。我试图使事情变得简单,可以在加载时运行的功能,检查是否设置了cookie-如果设置为“ true”,则随机更改图像src,如下所示:
HTML代码:
<img id="photo" src="../photostock/3129_382a101ee6d307dfd34abad8941c35cd_8885.jpg" alt="background" />
JS代码:
function rand_photo( id ) {
var q, img, id;
var random = function(min, max) {
return Math.Floor( Math.random() * ( max - min + 1 ) ) + min;
};
q = random( 1, 3 );
var prefix = '../photostock/',
suffix = '.jpg';
switch( q ) {
case 1:
img = '3129_382a101ee6d307dfd34abad8941c35cd_8885';
break;
case 2:
img = '1404_0d03ec48b64b4b65a6820aa5a58a39af_5487';
break;
case 3:
img = '1292_5d3c0fde3f83d725eb58025a522a6097_5648';
break;
default:
img = '7395_5d3c0fde3f83d725eb58025a522a6097_4191';
}
img = prefix + img + suffix;
document.getElementById( id ).setAttribute( 'src' ) = img;
// also tried with just ".src =" - didn't worked
}
function check_create_cookie( cookie_name, ident ) {
if( document.cookie.indexOf( cookie_name ) >= 0 ) {
rand_photo( ident )
}
else {
document.cookie = cookie_name + '=1; max-age=60';
}
}
window.onload = check_create_cookie( 'sample_cookie', 'photo' );
但由于某种原因,它不起作用...
有什么想法,笔记或两者兼有吗?
谢谢你们!
最佳答案
您的代码中有一些错字。
Math.Floor不存在:正确的格式为:Math.floor
document.getElementById(id).setAttribute('src')= img;是错的。
正确的格式是:document.getElementById(id).setAttribute('src',img);
有关详细信息,请参见MDN
最后一个是:window.onload = check_create_cookie('sample_cookie','photo');
MDN中正确描述了正确的格式
因此,工作代码为:
function rand_photo(id) {
var q, img, id;
var random = function(min, max) {
return Math.floor(Math.random() * ( max - min + 1 ) ) + min;
};
q = random( 1, 3 );
var prefix = '../photostock/',
suffix = '.jpg';
switch( q ) {
case 1:
img = '3129_382a101ee6d307dfd34abad8941c35cd_8885';
break;
case 2:
img = '1404_0d03ec48b64b4b65a6820aa5a58a39af_5487';
break;
case 3:
img = '1292_5d3c0fde3f83d725eb58025a522a6097_5648';
break;
default:
img = '7395_5d3c0fde3f83d725eb58025a522a6097_4191';
}
img = prefix + img + suffix;
document.getElementById(id).setAttribute('src', img);
// also tried with just ".src =" - didn't worked
}
function check_create_cookie( cookie_name, ident ) {
if( document.cookie.indexOf( cookie_name ) >= 0 ) {
rand_photo( ident )
}
else {
document.cookie = cookie_name + '=1; max-age=60';
}
}
window.onload = function() {
check_create_cookie( 'sample_cookie', 'photo' );
}
<img id="photo" src="../photostock/3129_382a101ee6d307dfd34abad8941c35cd_8885.jpg" alt="background" />