开发者

splice() not working on correctly

开发者 https://www.devze.com 2022-12-27 14:26 出处:网络
I am setting a cookie for each navigation container that is clicked on. It sets an array that is joined and set the cookie value.

I am setting a cookie for each navigation container that is clicked on.

It sets an array that is joined and set the cookie value. if its clicked again then its removed from the array.

It somehow buggy.

It only splices after clicking on other elements. and then it behaves weird.

It might be that splice is not the correct method

var navLinkToOpen;
var setNavCookie = function(value){
var isSet = false;
var checkCookies = checkNavCookie()
  setCookieHelper = checkCookies? checkCookies.split(","): [];
  for(i in setCookieHelper){
    if(value == setCookieHelper[i]){
       setCookieHelper.splice(value,1);
       isSet = true;
}
}
if(!isSet){setCookieHelper.push(value)}
setCookieHelper.join(",")
 document.cookie = "navLinkToOpen"+"="+setCookieHelper;
}


var checkNavCookie = function(){
var allCookies = document.cookie.split( ';' );
for (i = 0; i < allCookies.length; i++ ){
 temp = allCookies[i].split("=")
 if(tem开发者_运维知识库p[0].match("navLinkToOpen")){
  var getValue = temp[1]
  }
 }
return getValue || false
}



$(document).ready(function() {
  $("#LeftNav li").has("b").addClass("navHeader").not(":first").siblings("li").hide()
  $(".navHeader").click(function(){
$(this).toggleClass("collapsed").nextUntil("li:has('b')").slideToggle(300);
setNavCookie($('.navHeader').index($(this)))
return false
  }) 

var testCookies = checkNavCookie();
 if(testCookies){
finalArrayValue = testCookies.split(",")
for(i in finalArrayValue){
 $(".navHeader").eq(finalArrayValue[i]).toggleClass("collapsed").nextUntil(".navHeader").slideToggle   (0);
}

}
});


for(i in setCookieHelper){
    if(value == setCookieHelper[i]){

reads as:

for element in setCookieHelper

this element may not be an int and that causes your splice to fail, Also you must check if the element is contains the position where you want to splice then you must check if it's value is within the setCookieHelper lenght before you try to splice.

if you want to splice at a given position you should use a for:

for(i=0;i<setCookieHelper.lenght;i++){
     if(value == setCookieHelper[i]){
         setCookieHelper.splice(i,1);
         isSet = true;
     }
}

splice expects an index where to begin "splicing" and the amount of "spliced" elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消