页面加载时Javascript / JQuery Set Cookie

时间:2015-05-18 08:00:01

标签: javascript jquery html cookies

我希望在以下问题中有一些方向。

我想在页面加载时设置cookie。 Cookie值应取自HTML代码中的div data-myifo属性。

我目前的代码如下:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div id=someid data-myinfo="yyyyy">Hello World</div>

<script type="text/javascript">
function set_cookie (cookieName,cookieValue,nDays) {
    var today = new Date();
    var expire = new Date();
      if (nDays==null || nDays==0) nDays=1;
      expire.setTime(today.getTime() + 3600000*24*nDays);
      document.cookie = cookieName+"="+escape(cookieValue)
                       + ";expires="+expire.toGMTString() 
                       + "; path=/";
}

function get_atribute () {
    var myinfo = document.getElementsByTagName("div")[0].getAttribute("data-myinfo");
    set_cookie ("My_Cookie", myinfo);
}

$(document).ready(function () {
    get_atribute ();
});
</script>

</body>
</html>

我尝试使用get_atribute ()运行函数onclick="get_atribute ()",这种方式可以正常运行,但不会在页面加载时或之后运行。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

不需要在这里使用jQuery

可以使用:

(function() {
    get_attribute();
})();