简体   繁体   中英

How to get updated URL parameters after a jQuery change event

In Shopify, i'm trying to get the ID of the selected variant in a script file. I was able to get the Variant ID by getting the URL parameter, but it is giving me the url parameter that was there prior to the on change event.

I tried doing an AJAX call, looped through the product variant IDs but no luck.

// Getting the URL Parameter for Variant ID 
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
};


$('#option-color').change(function() {

  var currentUrl = getUrlParameter('variant');

  var variants = [];
  var selected = $(this).val(),
      mainImage = jQuery('.main-image img').attr('srcset'),
      maxCount = 0;

  $('.thumbnail').addClass('thumbnail--hidden');
  $('.thumbnail--last').addClass('thumbnail--last');
  arr = [];


  var addImage = $.each(images, function(i, image) {
    var alt = images[i].alt,
        url = images[i].url;

    if (( alt == selected || url == mainImage) && maxCount < 4) {
      $($('.thumbnail img[alt="' + alt + '"]')[maxCount]).parents('.thumbnail').removeClass('thumbnail--hidden');

      maxCount++
    }

  });

I basically want to be able to output the variant ID that it becomes after selecting on a new color.

When looking to get the variant ID of the currently selected variant, you should setup a listener on the actual element that changes the variant. All those active elements emit a type of "change" event you can listen to. When you get the change event, typically you get a variant to inspect, but if not, you can always query the element for its current value.

Looking in the URL is probably the least efficient and least trustworthy way to do this. Not all themes bother placing the current variant in the URL, and like you have pointed out, depending on when you choose to examine and parse that value, it might not represent what you want.

So the safest approach is examine the DOM and figure out the element the customer selected variants with, and dig through that to discover the "change" and subsequent value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM