我正在使用 JQuery cookie 库来隐藏/显示元素,然后在重新加载页面时记住状态。工作代码查找具有 id #num0 的元素并切换下一个元素,它看起来像这样:
if(Cookies('divShown0') == 'true') { //defaults to hidden
$('#num0').next().show(); // Show if cookie there and 'true'
}
$('#num0').click(function() {
$(this).next().toggle();
if(Cookies('divShown0') == 'true') {
Cookies.set('divShown0', 'false'); // Remember it was hidden
}
else {
Cookies.set('divShown0', 'true'); // Remember it was shown
}
});
我有多个,每个都由不同的#num 标识并存储为不同的 divShown 编号。到目前为止,我只是添加了一个带有新数字的新代码块,但显然这会占用大量空间。我将第一个 if() 语句放入 for() 循环中,没问题。第二部分我进入了一个函数 toggleShown(num),因此我可以调用 $('#num0').click(toggleShown(0));
,但这不起作用。我怀疑有关 $(this) 元素的某些内容没有正确标识下一个元素,但我真的不知道。
function toggleShown(num)
{
$(this).next().toggle();
if(Cookies('divShown' + num) == 'true') {
Cookies.set('divShown' + num, 'false'); // Remember it was hidden
}
else {
Cookies.set('divShown' + num, 'true');
}
}
我并不真正使用 Javascript 或 JQuery,主要是 RoR,但我正在尝试将其整合在一起。对我搞砸的事情有什么想法吗?
最佳答案
你的预感是对的! $(this)
函数内部不包含对原始元素的引用,因为您处于具有新作用域的新函数中。
你所要做的就是改变:
$(this).next().toggle();
到
$("#num"+ num).next().toggle();
关于javascript - 将 jQuery/JS 代码分解为 .click() 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32614580/