使用javascript保存和加载后台
这是我网站上的代码:你可以看到一个带有一些选项的下拉列表的使用javascript保存和加载后台,javascript,jquery,html,Javascript,Jquery,Html,这是我网站上的代码:你可以看到一个带有一些选项的下拉列表的select。单击某个选项时,后台将加载onchange()事件 <select id="rds" onchange="bg(this[this.selectedIndex].value);"> <option value="0.png">1. Default</option> <option value="1.png">2. Collage</option>
select
。单击某个选项时,后台将加载onchange()
事件
<select id="rds" onchange="bg(this[this.selectedIndex].value);">
<option value="0.png">1. Default</option>
<option value="1.png">2. Collage</option>
<option value="2.jpg">3. Darkness</option>
</select>
这很好用。我必须保存用户选择的选项,这样每次他打开网页时,都可以看到他选择的背景
我想保存一个cookie
并加载它。因为我看到javascript有点棘手,所以我想我可以使用jQuery
,所以我做了如下:
<select id="rds" onchange="bg(this[this.selectedIndex].value); $.cookie("example", this[this.selectedIndex].value, {expires: 7});">
<option value="0.png">1. Default</option>
<option value="1.png">2. Collage</option>
<option value="2.jpg">3. Darkness</option>
</select>
保存cookie后如何加载背景?我必须调用
bg()
函数,但我不知道怎么做。首先,不要对[event]属性使用。它们已经过时,使维护更加困难。而是将事件附加到JS中。下面是一个jQuery示例,使用$.cookie()
:
您的语法错误如下:
<select id="rds" onchange="bg(this[this.selectedIndex].value); $.cookie("example", this[this.selectedIndex].value, {expires: 7});">
你应该这样写:
<select id="rds" onchange="bg(this[this.selectedIndex].value); $.cookie('example', this[this.selectedIndex].value, {expires: 7});">
请注意“示例”周围的简单引用。在您的示例中,您使用的双引号干扰了html属性的双引号。您的语法错误是因为您没有在onchange事件中转义引号,请将其更改为:
<select id="rds" onchange="bg(this[this.selectedIndex].value); $.cookie('example', this[this.selectedIndex].value, {expires: 7});">
<option value="0.png">1. Default</option>
<option value="1.png">2. Collage</option>
<option value="2.jpg">3. Darkness</option>
</select>
1.违约
2.拼贴画
3.黑暗
要加载后台,请使用其他答案的解决方案:)。尝试将html和javascript/jquery分开。非常好的jquery示例要确保在加载jquery之前不调用setBackground函数,应执行以下操作:$(function(){setBackground($.cookie('bgImg');})代码>@SAUPWEB很好,谢谢。为了清晰起见,添加到了答案中。您是否包含cookie插件?它在jQuery中不是标准的。没错。您可以删除bg()
,因为它将不再使用。
var setBackground = function(bgImg) {
$.cookie('bgImg', bgImg);
$('body').css('background-image', 'url(http://mk7vrlist.altervista.org/backgrounds/' + bgImg + ')');
}
$(function() {
// on select change
$('#rds').change(function() {
setBackground($(this).val());
});
// on load
setBackground($.cookie('bgImg'));
});
<select id="rds" onchange="bg(this[this.selectedIndex].value); $.cookie("example", this[this.selectedIndex].value, {expires: 7});">
<select id="rds" onchange="bg(this[this.selectedIndex].value); $.cookie('example', this[this.selectedIndex].value, {expires: 7});">
<select id="rds" onchange="bg(this[this.selectedIndex].value); $.cookie('example', this[this.selectedIndex].value, {expires: 7});">
<option value="0.png">1. Default</option>
<option value="1.png">2. Collage</option>
<option value="2.jpg">3. Darkness</option>
</select>