Javascript 有人能帮我调试一个';每节课一次';带有addClass&;removeClass函数?
我发现了下面的JS代码(根本不是我的,我没有任何功劳。功劳归于Michael Regan,www.owt4nowt.ca) 因此,守则:Javascript 有人能帮我调试一个';每节课一次';带有addClass&;removeClass函数?,javascript,session,cookies,addclass,Javascript,Session,Cookies,Addclass,我发现了下面的JS代码(根本不是我的,我没有任何功劳。功劳归于Michael Regan,www.owt4nowt.ca) 因此,守则: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script> var key_value = "myTestCookie=true"; var
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var key_value = "myTestCookie=true";
var foundCookie = 0;
// Get all the cookies from this site and store in an array
var cookieArray = document.cookie.split(';');
for(var i=0;i < cookieArray.length;i++)
{
var checkCookie = cookieArray[i];
while (checkCookie.charAt(0)==' ')
{
checkCookie = checkCookie.substring(1,checkCookie.length);
}
if (checkCookie.indexOf(key_value) == 0)
{
alert("Found Cookie ");
foundCookie = 1;
}
}
if ( foundCookie == 0)
{
document.cookie = key_value;
alert("Setting Cookie");
}
</script>
我用addClass函数替换了“设置Cookie”警报,或者我是这么想的
if ( foundCookie == 0)
{
document.cookie = key_value;
$('.someClassHere').addClass("newClass");
}
问题是这个函数根本不起作用。如果只剩下警报,则没有问题,但addClass函数将被完全忽略
addClass函数有语法错误吗?在收到许多好的评论和提示后,在“alun”建议将javascript包装到jQuery.ready()API中之后,获得了最佳结果 脚本在添加(或删除)类方面的有效性有明显的延迟,但至少功能是存在的,通过CSS等的正确组合,中断可以最小化 我使用的成功代码是:
<script type="text/javascript">
$(document).ready(function () {
var key_value = "myTestCookie=true";
var foundCookie = 0;
var cookieArray = document.cookie.split(';');
for(var i=0;i < cookieArray.length;i++)
{
var checkCookie = cookieArray[i];
while (checkCookie.charAt(0)==' ')
{
checkCookie = checkCookie.substring(1,checkCookie.length);
}
if (checkCookie.indexOf(key_value) == 0)
{
foundCookie = 1;
}
}
if ( foundCookie == 0)
{
document.cookie = key_value;
$('.someClassOne').removeClass("extraClass");
}
});
</script>
$(文档).ready(函数(){
var key_value=“myTestCookie=true”;
var=0;
var cookieArray=document.cookie.split(“;”);
for(var i=0;i
所以,是的,我希望这能帮助别人
谢谢论坛
/布莱恩你漏掉了一个真正的问题!有些东西不起作用了吗?你有错误吗?我更新了帖子,谢谢你的提醒,看起来你在尝试使用jQuery-你有没有包含jQuery库?我已经包含了谷歌1.7.2链接你能在你的问题中添加你是如何链接到jQuery的吗。
<script type="text/javascript">
$(document).ready(function () {
var key_value = "myTestCookie=true";
var foundCookie = 0;
var cookieArray = document.cookie.split(';');
for(var i=0;i < cookieArray.length;i++)
{
var checkCookie = cookieArray[i];
while (checkCookie.charAt(0)==' ')
{
checkCookie = checkCookie.substring(1,checkCookie.length);
}
if (checkCookie.indexOf(key_value) == 0)
{
foundCookie = 1;
}
}
if ( foundCookie == 0)
{
document.cookie = key_value;
$('.someClassOne').removeClass("extraClass");
}
});
</script>