Uncaught SyntaxError: Unexpected token ')' в пользовательском файле js, предназначенном для магазина Shopify

Я добавил пользовательский файл .js в магазин Shopify. Несмотря на множество попыток, мне кажется, что я не могу найти причину этой ошибки. Пожалуйста, проверьте приведенный ниже код, чтобы сообщить мне, где мне нужно исправить код, чтобы исправить ошибку. Исправление других проблем, указанных кодом VS, не помогает исправить ошибку. Я внимательно искал начало и закрывающие фигурные скобки в каждом блоке кода / функции.

// Listener for variant:changed event in product page.
document.addEventListener('variant:changed', function(event) {
  var variant = event.detail.variant; // Gives access to variant details
  var fulfillment_info_str = "";
  var free_shipping_applicable = (variant.price >= (sku_free_shipping_threshold[variant.id] * 100)) ? true : false;

  // In the Variant Fulfillment Info, add the Back Order information or the Fulfillment Info
  if (sku_backorder_info[ variant.id ] != "") {
    fulfillment_info_str = sku_backorder_info[ variant.id ];
  } else {
    fulfillment_info_str = "In stock!  " + sku_fulfillment_info;
    if (!free_shipping_applicable) {
      fulfillment_info_str += ". Purchase $" + sku_free_shipping_threshold[variant.id] + " " +vendor_name+ " products for FREE shipping";
    }
  }
  document.querySelector(".variant-fulfillment-info").innerHTML = fulfillment_info_str;
});


//  var vendor_name= $(".ProductMeta__Vendor").text();

//$('h2').hide();
//$('body').append("vendor name = " + vendor_name);
//$('body').append(jQuery.fn.jquery);

var loadScript = function(url, callback){
    var script = document.createElement("script")
    script.type = "text/javascript";
 
    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }
 
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
};

if ((typeof jQuery === 'undefined') || (parseFloat(jQuery.fn.jquery) < 1.7)) {
  loadScript('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', function(){
    jQuery191 = jQuery.noConflict(true);
    myAppJavaScript(jQuery191);
  });
} else {
  myAppJavaScript(jQuery);
}

var myAppJavaScript = function($){
 // $('h2').hide();
//$('body').append(jQuery.fn.jquery);
 // $('body').append('<p>Your app is using jQuery version '+$.fn.jquery+'</p>');
};

// change the menu icon from click to mouseover
var myAppJavaScript = function($){

  $(".Icon-Wrapper").mouseover(function(){
  $(this).trigger("click");
  });
  
// the little circle and down-arrown on main home page - CHARCOAL and BLACK 3/23/2020 AB
//  $(".Slideshow__ScrollButton").css("background-color","#6A6A6A")   
  $(".flickity-viewport").after('<div style = "padding-left:10px;text-align:center;color:#000000;font-weight:bold;">MORE &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BELOW</div><br />')

// Electric Mirror backlit mirrors - changes
  if ((document.title.indexOf("Electric Mirror")>-1 && document.location.href.indexOf("backlit")>0) || document.location.href.indexOf("tv")>0){  
    // correct the shipping time
    $(".variant-fulfillment-info").html('<span style = "font-size:1.1em">Shipped <span style = "font-weight:bold;color:#0000FF">FREE</span> in about 1 week, direct from the factory.</span>');
    // get "Backlit Size" to appear as "Size"
    var sizetext= $(".ProductForm__OptionName").html();
    $(".ProductForm__OptionName").html(sizetext.replace("Backlit ",""));
  }
  
// Phrase appears beneath the header logo - commented
//$(".Header__LogoImage--transparent, .Header__LogoImage--primary").after('<br /><div style = "display:none" id = "free49">FREE SHIPPING over $49</div>');
//  $( window ).scroll(function() {
//    $("#free49").show();
//  });  

//  *******************  copy of PMM custom.js file  ******************************************************************

function get_pmm_shipping_text() {
    var v_text = "",page_title,meta_string,pmm_vendor_code,pmm_price,pmm_sku,
    meta,meta_string,
    exceptions = "KE OM TB JV E_M EL",
    notFree = "BB,LC,TB,JA,MD",
    ship_info = "",cost = "",free = "",p=0,q=0,weeks = "",
    little_box= '<img src = "https://cdn.shopify.com/s/files/1/0048/2675/9279/t/9/assets/free-shipping.png" class = "altattr" alt = "Free Shipping">',
    little_plane= '<img src = "https://images.reflectperfection.com/5f89061a4c6ab.png" class = "altattr" alt = "Air Express">';
    
    //  get the vendor, sku, and price
    meta_string = JSON.stringify(meta);
    meta_string = meta_string.replace(/[/{\}\[\]\"]/g, '');
    
    p = meta_string.indexOf("sku");
    pmm_vendor_code = meta_string.substr(p+4,2);
    q = meta_string.substr(p+4).indexOf(",");
    pmm_sku = meta_string.substr(p+4,q);
    pmm_sku = pmm_sku.replace(/[\-P\-]/,"");
    p = meta_string.indexOf("price");
    q = meta_string.substr(p+6).indexOf(",");
    pmm_price = meta_string.substr(p+6,q);
            
    // NOTE:  pmm_vendor_code, pmm_sku and  pmm_price are pre-existing variables
    console.info("Vendor Code = " + pmm_vendor_code + ", SKU = " + pmm_sku + "Price = " + pmm_price);

    notFree.indexOf(pmm_vendor_code)>-1 ? free = "" : free = "FREE,"; // if prefix not in "notFree" variable, shipping is FREE regardless of price.
    pmm_price > 4900 ? free = "FREE," : free = "" ; // everything over $49 ships free.
    // thresh>"" && netprice<thresh ? free = "" : ''; // below shipping threshold nullifies free shipping  (thresh and netprice are not defined)
    if (pmm_vendor_code == "EM" || pmm_vendor_code == "E2" ){ // handles Electric Mirror mirror types
        page_title = $(".ProductMeta__Title").text();
        
        if (page_title.indexOf("TV")>-1){
            weeks = "4 to 6";
        }
        if (page_title.indexOf("Smart")>-1){
            weeks = "6 to 8";
        }
        if (page_title.indexOf("Backlit")>-1){
            weeks = "1 to 2";
        }
        if (page_title.indexOf("Shower")>-1 || page_title.indexOf("Cabinet")>-1){
            weeks = "2";
        }
        if (page_title.indexOf("Wardrobe")>-1){
            weeks = "3 to 4";
        }
        if (weeks > "" ){
            document.getElementsByClassName("available")[0].innerText = ""; // eliminates IN STOCK from page
            pmm_vendor_code = "E_M"; 
        }
    }
    
    switch(pmm_vendor_code){  // exceptions items to vendor Free or Not-Free
        case "BB" : pmm_sku == "BB01" ? free = "FREE," : '' ;
        case "JA" : pmm_price > "32" ? free = "FREE," : '';
        case "MD" : pmm_price > "32" ? free = "FREE," : '';
        case "LC" : pmm_price > "57" ? free = "FREE," : '';
    }

    // REMEMBER free (lower case) is a variable
    cost = "In stock! &nbsp;Shipped "+free+" usually on the ";
    switch (pmm_vendor_code){
        case "AA" : ship_info=cost+"3<sup>rd</sup> to 5<sup>th</sup> " ; break; // Aamsco
        case "AB" : ship_info=cost+"1<sup>st</sup> or 2<sup>nd</sup> " ; break; // Amba
        case "AG" : ship_info=cost+"1<sup>st</sup> or 2<sup>nd</sup> " ; break; // alkaglam
        case "AY" : ship_info=cost+"2<sup>nd</sup> to 4<sup>th</sup> "; break; // ayurderm
        case "BB" : ship_info=cost+"next " ; break; // NOT free -butterbabes
        case "CL" : ship_info=cost+"2<sup>nd</sup> to 4<sup>th</sup> " ; break; // clear mirror
        case "CB" : ship_info=cost+"same or next "; break; // cannaBon
        case "CP" : ship_info=cost+"1<sup>st</sup> or 2<sup>nd</sup> " ; break;  // contrapac
        case "CY" : ship_info=cost+"same or next " ; break;  // cyberderm
        case "DB" : ship_info=cost+"same or next " ; break; // Dear by Renee
        case "DN" : ship_info=cost+"next " ; break;  // dia naturals
        case "E3" : ship_info=cost+"3<sup>rd</sup> to 6<sup>th</sup> " ; break; // electric mirror Cordova brand
        case "EM" : ship_info=cost+"4<sup>th</sup> to 6<sup>th</sup> " ; break; // electric mirror
        case "FS" : ship_info=cost+"2<sup>nd</sup> " ; break; // foster and lake
        case "GH" : ship_info=cost+"1<sup>st</sup> or 2<sup>nd</sup> " ; break; // stan pardente ghd
        case "HR" : ship_info=cost+"same or next "; break; // hair restoration
        case "JA" : ship_info=cost+"same or next " ; break;  // JAVA skin care
        case "JD" : ship_info=cost+"3<sup>rd</sup> to 5<sup>th</sup> ";break; // Jerdon
        case "KY" : ship_info=cost+"1<sup>st</sup> or 2<sup>nd</sup> "; break;  // kimball & young / aptations
        case "LC" : ship_info=cost+"same or next "; break;  // l.a. christine
        case "LD" : ship_info=cost+"2<sup>nd</sup> "; break; // lumidesign
        case "LU" : ship_info=cost+"same or next "; break;  // luce skincare
        case "LW" : ship_info=cost+"1<sup>st</sup> or 2<sup>nd</sup> " ; break; // stemulation
        case "MD" : ship_info=cost+"1<sup>st</sup> or 2<sup>nd</sup> "; break; // MDSolarSciences
        case "MH" : ship_info=cost+"2<sup>nd</sup> to 3<sup>rd</sup> " ; break; // more hair naturally
        case "MY" : ship_info=cost+"2<sup>nd</sup> to 3<sup>rd</sup> " ; break; // marcus york
        case "RE" : ship_info=cost+"same or next "; break; // replete skincare
        case "NO" : ship_info=cost+"same or next "; break; // gentleman's foundry
        case "SK" : ship_info=cost+"next " ; break; // skin triks
        case "SQ" : ship_info=cost+"same or next " ; break; // skintifique
        case "SY" : ship_info=cost+"2<sup>nd</sup> or 3<sup>rd</sup>" ; break; // shunly
        case "TB" : ship_info=cost+"2<sup>nd</sup> or 3<sup>rd</sup>" ; break; // to bee products
        case "TH" : ship_info=cost+"1<sup>st</sup> or 2<sup>nd</sup> " ; break; // thalgo
        case "UC" : ship_info=cost+"2<sup>nd</sup> to 4<sup>th</sup>";break; // upper canada (danielle creations)
        case "VT" : ship_info=cost+"next " ; break;  // vintage traditions
        case "xx" : ship_info=cost+"same or next"; break; // pmm inventory product
    }
    console.info("Ship Info = " + ship_info);
    

    if (exceptions.indexOf(pmm_vendor_code)==-1){ // if vendor is NOT in the exceptions string cases above are used
            if (free= = "FREE," ){ // display the little truck 
                v_text = little_box + ' &nbsp;<strong>' + ship_info + ' business day.</strong>';
            } else { // no little truck
                v_text = '<strong> ' + ship_info +' business day.</strong>';
            }
    } else { // following vendors must be included in the exceptions string on or near  line 4
        switch (pmm_vendor_code){
            case "EL" : v_text = '<span style = "color:#A300FC;font-size:1.1em;font-weight:bold" >'+little_plane+' &nbsp;Formulated in the EU,  and Shipped FREE, directly to your door via Royal Mail International from Kent, England in 7-8 days.</span>'; break;
            case "E_M" : v_text = '<span style = "color:#A300FC;font-size:1.1em;font-weight:bold" >'+little_box+' &nbsp;Custom made for you in the USA, and Shipped FREE, directly to your door via <span style = "color:#4D148C;font-weight:bold">Fed</span><span style = "color:#FF6200;font-weight:bold">Ex</span> or by Truck, in '+weeks+ ' weeks, directly from the Washington State factory.</span>'; break; 
            case "JV" : v_text = '<span style = "color:#A300FC;font-size:1.1em;font-weight:bold" >'+little_plane+' &nbsp;Made in France, Shipped FREE, directly to you via <span style = "color:#4D148C;font-weight:bold">Fed</span><span style = "color:#FF6200;font-weight:bold">Ex</span> International Express</span> in about 7-10 days, directly from the Mexico warehouse.</span>'; break; // JVD
            case "KE" : v_text = '<span style = "color:#A300FC;font-size:1.1em;font-weight:bold" >'+little_plane+' &nbsp;Shipped FREE, directly to you via <span style = "color:#4D148C;font-weight:bold">Fed</span><span style = "color:#FF6200;font-weight:bold">Ex</span> International Express</span> in about 21 days, directly from Germany.</span>'; break; // Keuco
            case "OM" : v_text = '<span style = "font-size:1.1em;font-weight:bold">'+little_box+' 8 oz. size ships FREE.<br />Also shipped FREE: &nbsp;2 oz. size purchased together with 8 oz. size - or - 3 or more 2 oz. size.<br /><br />Shipment is from Canada after 1 business day. &nbsp;Time in transit to locations in the continental US is 3 to 5 business days.</span>'; break;  // oil me north
            case "TB" : v_text = '<span style = "font-size:1.1em;font-weight:bold">Ships FREE when purchased together with ToBee 3-Pack</span>'; break;  // to bee products
        }
    }
    console.info("V Text = " + v_text);
    return v_text;
}); // end of get_pmm_shipping_text()

// ---------------------------------  miroir brot vacation --------------------------------------------------------

    /*if (docloch.indexOf("miroir-brot")>-1){
            var brot_start = new Date(2019,06,28),
                brot_end = new Date(2019,07,30);
            if (today_date => brot_start && today_date <= brot_end){
                $(".product-name").after('<div id = "brot_vacation" style = "text-align: left;font-size: large; color: #9900ff;">Miroir Brot will be CLOSED for summer vacation from August 5th through August 30th.<br /><br /><strong>Order by <span style = "color: #ff0000;">Thursday, July 25th</span> for shipment before vacation closing.</strong><br /><br />Orders placed after July 25th will be shipped after August 30th.</div>');
            }
    } */

$(document).ready(function(v_text) {
    var page_title = $(".ProductMeta__Title").text();
    
    // Commented out as the Tab is not opening by default.
    // $("#tab-label-product.info.description").click();
    setTimeout(function() {             
        document.querySelector(".variant-fulfillment-info").innerHTML = v_text;
        //$(".variant_fulfillment-info").text(get_pmm_shipping_text()); }, 750); // end of setTimeout
    // make the word CLOSEOUT red on product pages
    if (page_title.indexOf("CLOSEOUT!")>-1 || page_title.indexOf("OPEN BOX!")>-1){
        page_title = page_title.replace("CLOSEOUT!",'<span style = "color:#FF0000">CLOSEOUT!</span>');
        page_title = page_title.replace("OPEN BOX!",'<span style = "color:#FF0000">OPEN BOX!</span>');
        $(".ProductMeta__Title").html(page_title);
    }

    // Normally add the bind to a parent which will be stable.
    
    // commented out following that deals with Klarna AB 10/22/2020
 /*   $("#product-options-wrapper select").change(function() {

      // setTimeout() used to ensure a time interval between Magento populating the span
      // and jQuery reading the span.
      setTimeout(function() {
        // Get the value of the span element
        var price = $(".price-box .normal-price .price-wrapper span.price").html();

        // Clean and Convert the value to cents
        var priceCents = parseInt(parseFloat(price.replace(/[^\d.]/g,'')) * 100);

        // If value is different from existing Klarna product placement value, update it.
        // and then call Klarna with refresh-event to refresh the placement.
        var oldPurchaseAmt = $(".product-add-form klarna-placement").attr("data-purchase-amount");
        if (priceCents != oldPurchaseAmt) {
          $(".product-add-form klarna-placement").attr("data-purchase-amount", priceCents);

          // Trigger event to refresh
          window.KlarnaOnsiteService = window.KlarnaOnsiteService || [];
          window.KlarnaOnsiteService.push({ eventName: 'refresh-placements' });
        }
      }, 200);
    }); */
}); // end of document.ready

//  *******************  end of copy of PMM custom.js file  ******************************************************************

  
} // end of jQuery

Вы закомментировали конец функции setTimeout в последнем блоке $ (document) .ready, поэтому он не закрывается должным образом.

Daniel Attfield 06.04.2021 11:38
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
1
30
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Неожиданный ) находится в PMM custom.js, где заканчивается get_pmm_shipping_text().

Кроме того, в том же файле, непосредственно перед }, отсутствуют ) и // end of document.ready.

Первая инструкция верна, вторая - нет - "отсутствует"}) принадлежит полностью закомментированной функции $ ("# product-options-wrapper select"). Change.

Daniel Attfield 06.04.2021 11:51

@DanielAttfield Я думаю, что он предназначен для соответствия с $("#product-options-wrapper select").change (в начале комментария)

Xenohon 06.04.2021 11:55

Другие вопросы по теме