根据单击的链接名称设置cookie
TLDR单击链接时,我想指定一个带有工具名称的cookie,并点击链接上的文本值。
使用Jquery.1.4.2.min.js,Jquery.cookie.1.0.js
我想在点击链接时创建一个cookie(将始终链接到“https://stackoverflow.com/questions/2756422/setting-a-cookie-based-on-the-name-of-the-link-that-is-clicked/page.html”)。
仪器名称
TEXT的值
到目前为止,我正在尝试使用:
链接1:
link1
链接2:
link2
脚本:
$('a[href=https://stackoverflow.com/questions/2756422/setting-a-cookie-based-on-the-name-of-the-link-that-is-clicked/page.html]').click(function() { var name = 'instrument'; var value = $(this).text(); $.cookie(name, value, { expires: 365 }); });
当我点击链接时,它只是加载链接,没有设置cookie。 使用firebug,firecookie,firequery进行调试。 没有找到仪器的cookie或沿线的任何东西。 Onload我会打的
“ projects
”但不是
“ $.cookie(name, value, { expires: 365 });
”完全没有。
即使使用以下:(感谢Sarfraz )
$('a[href="https://stackoverflow.com/questions/2756422/setting-a-cookie-based-on-the-name-of-the-link-that-is-clicked/page.html"]').click(function(e) { // prevent default action e.preventDefault(); var name = 'instrument'; // get link text var value = $(this).text(); // set cookie $.cookie(name, value, { expires: 365 }); // now go to link's location document.location.href = $(this).attr('href'); });
仍然不会创建cookie。
如果我在$.cookie~
上添加一个断点,即使单击其中一个链接,它也不会触及断点,也不会触及document.location.href~.
对于扎克:
Pre Render –
渲染后 –
" "
这是hackish,但它适用于我。
$(document).ready( function() { $('a.cookier').each( function() { // Kill the link's link feature. _href = $(this).attr('href'); $(this).attr("rel", _href).attr("href", "javascript:void(0);"); }); $('a.cookier').click(function() { var name = 'instrument'; var value = $(this).text(); $.cookie(name, value, { expires: 365 }); // Go places document.location.href = $(this).attr('rel'); }); });
我的标记看起来像这样:
Shazam!
我使用类似的方法在使用AJAX的页面上“取消链接”我的链接,但必须优雅地降级。
注意:你可能想要选择一个比“cookier”更高级的课程。
编辑:
您可以选择其中任何一个的那些
,选择哪个不选择页面上的其他东西。
.dtree img + a .dTreeNode > a .dTreeNode a.node .dTreeNode a[onclick=|javascript].node
var value = $(this);
将jQuery对象赋值给value。 使用
var value = $(this).text();
要么
var value = $(this).attr('href');
试试这个:
$('a[href="page.html"]').click(function(e) { // prevent default action e.preventDefault(); var name = 'instrument'; // get link text var value = $(this).text(); // set cookie $.cookie(name, value, { expires: 365 }); // now go to link's location document.location.href = $(this).attr('href'); });
使用上面Zack的答案我改变了元素标签。 唯一的问题是,它会为我想要或不想要的链接所遵循的任何链接设置cookie,但它设置cookie并在需要的地方工作。 如果有一个更清洁的方法,将不胜感激。
$(document).ready( function() { $('a[href="page.html"]').each( function() { // Kill the link's link feature. _href = $(this).attr('href'); $(this).attr("rel", _href).attr("href", "javascript:void(0);"); }); $('a').click(function() { var name = 'instrument'; var value = $(this).text(); $.cookie(name, value, { expires: 365 }); // Go places document.location.href = $(this).attr('rel'); }); });
非常感谢Sarfraz和Zack的所有帮助,至少我有一些现在有用的东西^^