0

我在 Firefox 中将此用作书签,但是当我访问该页面并尝试加载书签时,它什么也没做。我的 JS 代码有问题吗?

在用户 KURT 的建议下,我能够通过以下方式解决这个问题:

javascript: (function () {
    function getCookie(name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf( 'JSESSIONID' + '=');
            if (c_start != -1) {
                c_start = c_start + 'JSESSIONID'.length + 1;
                c_end = document.cookie.indexOf(';', c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end))
            }
        }
        return null;
    }

    function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
    }


    var thedc = readCookie("dc"); 

    if (thedc.substring(0, 2) == 'SP') { 
        alert(' in SP ');
    } else {
        alert(' in WC '); 
    }

}());
4

1 回答 1

1

您需要将其包装在自调用函数中。

(function() { /* Your code */ })();

您的 getDC 函数还需要显式调用,因此需要调用它。

javascript: (function () {
    function getCookie(cookieName) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf( cookieName + '=');
            if (c_start != -1) {
                c_start = c_start + cookieName.length + 1;
                c_end = document.cookie.indexOf(';', c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end))
            }
        }
        return null;
    }

    var thedc = getCookie("dc"); 

    if (thedc.substring(0, 2) == 'SP') { 
        alert(' in SP ');
    } else {
        alert(' in WC '); 
    }
}());

并压缩:

javascript:(function(){function e(){if(document.cookie.length>0){c_start=document.cookie.indexOf(cookieName+"=");if(c_start!=-1){c_start=c_start+cookieName.length+1;c_end=document.cookie.indexOf(";",c_start);if(c_end==-1)c_end=document.cookie.length;return unescape(document.cookie.substring(c_start,c_end))}}return null}var t=e("dc");if(t.substring(0,2)=="SP"){alert(" in SP ")}else{alert(" in WC ")}})()
于 2012-11-14T17:37:00.273 回答