jQuery .attr('id') 返回空
这是我的代码
$('.sort').click(function(){
console.log($(this).attr('id'));
$.cookie('sortby', $(this).attr('id'), { expires: 25 });
//window.location.reload(true);
});
HTML
<button id="name" class="sort">Name</button>
<button id="price" class="sort">Price</button>
<button id="popular" class="sort">Popularity</button>
我的 cookie 最终为空,控制台显示为
popular
(an empty string)
似乎它正在获取正确的 id,但随后将其更改为 null 有什么建议吗?
Here is my code
$('.sort').click(function(){
console.log($(this).attr('id'));
$.cookie('sortby', $(this).attr('id'), { expires: 25 });
//window.location.reload(true);
});
HTML
<button id="name" class="sort">Name</button>
<button id="price" class="sort">Price</button>
<button id="popular" class="sort">Popularity</button>
My cookie ends up empty and the console shows up as
popular
(an empty string)
It seems it is getting the correct id but then changing it to null
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在第二次调用中, $(this) 对象已更改范围。以下应该有效:
In your second call the $(this) object has changed scope. The following should work:
我认为那是因为当你提到“这个”时,你的内部cookie会尝试代替
I think that's because your inside cookie when you refer to 'this' try instead
不确定您的代码哪里出了问题,因为我无法重现该问题。
我会确保
$.cookie
库正在加载,并确保一切顺利。Not sure where your code is going wrong, as I can not reproduce the issue.
I would look in to making sure the
$.cookie
library is loading and make sure things are good on that end.