我有以下情况:

用户将鼠标悬停在菜单项上,然后将鼠标悬停在外部站点上,会调用Javascript脚本。该脚本将内容写入特定的div。

然后,我需要做的就是抓取这个divs html并将其存储在cookie中。 Cookie会在3分钟后过期。

用户第二次在3分钟内停留(cookie尚未过期),而不是从外部站点调用Java脚本,而是需要简单地加载以前由Java脚本从外部站点写入div的HTML。这是为了限制对外部站点的呼叫数量,因为它会对向其服务器的每次呼叫收费。

因为从外部站点的Javascript编写内容并将分配的html值分配给cookie是在客户端同时发生的,所以在尝试将html存储到cookie中时,我总是没有任何价值。

我需要某种方式等待页面完全加载,以便外部脚本用HTML内容填充指定的div,然后将div的html内容添加到cookie中。

这就是我遇到的问题。也许对此有一种更简单,更聪明的方法?我乐于接受建议和想法!

这是我有注释的代码:

$(document).ready(function() {

    // create script element
    var my_script = document.createElement( 'script' );
        my_script.type = 'text/javascript';
        my_script.src = "http://www.external-site.com/this_script_writes_content_to_div.js";

    // User hovers on a menu item, limit the call by using jQuery .one
    $( "#my_menu_item" ).one( "mouseenter", function() {

        // If cookie exists, don't write Javascript (my_script) but use stored value in cookie
        if (document.cookie.indexOf("my_cookie") != -1) {

            // This is where I'm having trouble, since the cookie's value is empty, see below
            $("#div_with_content_from_js").html( getCookie("my_cookie") );

            // Test results
            console.log('Cookie exists');
            console.log(getCookie("my_cookie"));
        }

        // If cookie does not exist, write the script to a div
        // the script will then populate another div with content, the div name is 'div_with_content_from_js'
        // then create cookie and store the other divs content into the cookie
        else {
            document.getElementById( "div_for_external_script" ).appendChild( my_script );
            create_my_cookie();

            // test results
            console.log( 'Cookie does not exist' );
        }
    });

});


// Creates a cookie that expires after 180 seconds (3 minutes)
function create_my_cookie() {
    var date = new Date();
    date.setTime( date.getTime() + ( 180*1000 ) );
    var expires = "; expires="+date.toGMTString();

    // this value returns empty because the html value of div_with_content_from_js was just written (see else part above)
    // this is where I'm stuck, how do I get the value of div_with_content_from_js and store it in the cookie
    var coffee_cookie_value = $("#div_with_content_from_js").html();

    document.cookie = 'my_cookie' + "=" + coffee_cookie_value + expires + "; path=/";

    // test results
    console.log( coffee_cookie_value );
    console.log( getCookie( "my_cookie" ) );
}


// This function returns a specific cookie, used for testing
function getCookie( name ) {
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec( document.cookie );

    return ( value != null) ? unescape(value[1] ) : null;
}

最佳答案

Cookie仅用于倒计时3分钟
在页面上添加隐藏的div
在隐藏的div中,存储来自外部网站的内容
悬停时:如果未过期3分钟,只需复制隐藏的div的内容

关于jquery - jQuery/Javascript:使用脚本编写的数据填充div,而不是将div的值存储到cookie中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27302449/

10-12 12:26
查看更多