jQuery .attr('id') 返回空

发布于 2024-11-13 11:29:23 字数 575 浏览 4 评论 0原文

这是我的代码

    $('.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦里泪两行 2024-11-20 11:29:23

在第二次调用中, $(this) 对象已更改范围。以下应该有效:

    $('.sort').click(function(){
        console.log($(this).attr('id'));
        var $this = $(this);
        $.cookie('sortby', $this.attr('id'), { expires: 25 });
        //window.location.reload(true);
    });

In your second call the $(this) object has changed scope. The following should work:

    $('.sort').click(function(){
        console.log($(this).attr('id'));
        var $this = $(this);
        $.cookie('sortby', $this.attr('id'), { expires: 25 });
        //window.location.reload(true);
    });
吝吻 2024-11-20 11:29:23

我认为那是因为当你提到“这个”时,你的内部cookie会尝试代替

$('.sort').click(function(){
    var id = $(this).attr('id')
    $.cookie('sortby', id, { expires: 25 });
});

I think that's because your inside cookie when you refer to 'this' try instead

$('.sort').click(function(){
    var id = $(this).attr('id')
    $.cookie('sortby', id, { expires: 25 });
});
方觉久 2024-11-20 11:29:23

不确定您的代码哪里出了问题,因为我无法重现该问题。

我会确保 $.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文