Home  >  Q&A  >  body text

The process of determining whether an element exists in an array is invalid

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粉204136428P粉204136428180 days ago387

reply all(1)I'll reply

  • P粉364129744

    P粉3641297442024-04-04 11:01:12

    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>

    reply
    0
  • Cancelreply