The process of determining whether an element exists in an array is invalid
P粉204136428
P粉204136428 2024-04-03 13:03:54
0
1
474

Sorry to bother you, but I've spent two hours solving this problem. The problem is that my code only adds one element, but does not add other ids, it writes "already exists"

$(function(){

    $(".js-compare-add").click(function(){
        var item_id = $(this).data('id');

        if(Cookies.get('compare_id_list')){
            var compareListStr = Cookies.get('compare_id_list');
            var compareListArr = compareListStr ? compareListStr.split(',') : [];
            if (compareListArr.indexOf(item_id) > -1) {
                compareListArr.push(item_id);
                Cookies.set('compare_id_list', compareListArr.join(','), {expires: 10}); 
                alert('Save! ' + item_id);
            } else {
                alert('already have ' + item_id);
            }

        } else {
            alert('There was no list, we created it and added this position ' + item_id);
            Cookies.set('compare_id_list', item_id);
        }

    });
});

Just in case - I use this for cookies https://github.com/js-cookie/js-cookie if (jQuery.inArray(item_id,compareListArr) === -1) doesn't help either

P粉204136428
P粉204136428

reply all(1)
P粉364129744

Dave Newton made a useful point, the logic seems backward, but if this is what you get if you try to make it work:

When you use the data function, jQuery does data manipulation and does more than just give you the string value of the matching data-id attribute. If the attribute's text is all numeric, jQuery will convert it to a number:

const id = $("#example").data("id");
console.log(typeof id); // number
<div id="example" data-id="123"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!