我正在使用以下代码来生成一个内容区域,该区域在点击时打开和关闭,同时加/减图像也根据内容区域的状态切换。我想要做的是添加一个jQuery Cookie,以节省内容区域的状态 - 我将如何实现这一目标?小号将jquery cookie添加到内容切换
$(document).ready(function() {
$("a.toggle").click(function() {
var img = $(this).find("img"); //get a handle of the image tag inside title link
var src = $(img).attr("src"); //get the source of the image
//toggle the source of the image to show either plus/minus
if (src.endsWith("search_open.jpg"))
src = src.replace('search_open.jpg', 'search_close.jpg');
else
src = src.replace('search_close.jpg', 'search_open.jpg');
$(img).attr("src", src);
//get the title of the anchor tag which corresponds to the id of the content div
var content = $(this).attr("title");
$(content).toggle();
});
});
String.prototype.endsWith = function(str) {
return this.lastIndexOf(str) == this.length - str.length;
}
编辑:最后的代码/解决方案
$(document).ready(function() {
$("a.toggle").each(function() {
var img = $(this).find("img");
var src = $(img).attr("src");
var content = $(this).attr("title");
var isVisible = $.cookie('content');
if (isVisible == 'true') {
$(content).show();
src = src.replace('search_open.jpg', 'search_close.jpg');
}
$(img).attr("src", src);
});
$("a.toggle").click(function() {
var img = $(this).find("img"); //get a handle of the image tag inside title link
var src = $(img).attr("src"); //get the source of the image
//toggle the source of the image to show either plus/minus
if (src.endsWith("search_open.jpg"))
src = src.replace('search_open.jpg', 'search_close.jpg');
else
src = src.replace('search_close.jpg', 'search_open.jpg');
$(img).attr("src", src);
//get the title of the anchor tag which corresponds to the id of the content div
var content = $(this).attr("title");
$(content).toggle();
$.cookie('content', $(content).is(':visible'));
});
});
String.prototype.endsWith = function(str) {
return this.lastIndexOf(str) == this.length - str.length;
}
谢谢 - 我使用jquery.cookie并使用它 - 我似乎没有能够将它集成到我的代码。 – ss888
我还没有改变检查它,但这个想法是在示例中。如果您的内容的默认状态处于隐藏状态,它将起作用 – Samich
辉煌 - 不得不稍微调整你的代码(最终代码添加到原始问题) - 非常感谢,S – ss888