Home > Software engineering >  .each loop is not working in my jQuery code
.each loop is not working in my jQuery code

Time:05-28

The code below is written to hide the "IN STOCK" phrase on certain vendors' product pages. I noticed the loop itself isn't running when I used console.log. Could you please help correct the code?

function runPmmCustomAllPagesJs($) {
    // This function is called from argento-custom.js once dom is ready and jQuery obect is available.
    // $ has the jQuery object.

    var docloch = document.location.href,
        scree = [screen.availWidth, screen.availHeight],
        thisVal = "",
        tAlign = "left",
        afterwhat = "h3",
        df,
        hide_inStock= [':"JV', ':"KE', ':"MB', ':"WD'],
        doc_text=$(document).text(),
        v_code;
        
        
    // hides the "IN STOCK" phrase on certain vendors' product pages
    $(hide_inStock).each(function(v_code){
        console.log('v_code: '   v_code);
        if (doc_text.indexOf(v_code)>1){
            $(".stock").hide();
            return false;
        }
    });
}

CodePudding user response:

When false is returned from the predicate, the iteration is ended prematurely. Return something else or even nothing if you want it to get to the end.

Also, remember that the first argument passed to .each is the index.

$([1, 2, 3]).each((_index, value) => {
    console.log(value);

    if (value === 2) {
        return false;
    }
});
// 1
// 2
  • Related