2015-05-18 153 views
0

我希望在下面的问题的一些方向。Javascript/JQuery设置Cookie页面加载

我想在页面加载时设置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> 

我试着用onclick="get_atribute()"和它的工作方式,但不是在页面加载或后运行的功能get_atribute()

我错过了什么?

+0

您还没有包括jQuery的库文件。由于这个你的document.ready函数没有执行。 –

+0

@SameerK你是对的!非常感谢你指出! –

回答

0

无需使用jQuery这里

可以只使用:

(function() { 
    get_attribute(); 
})(); 
+0

谢谢。这样做的工作。我感谢您的帮助! –