如何使用多个url参数来显示/隐藏多个div

Hoping to find a way to have multiple URL parameters display specific divs for certain products, while hiding all the other product divs.

For example:

website.com/?product=widget1,widget3,widget4

or

website.com/?product=widget1&product=widget3&product=widget4

The above would display the 3 divs associated with each of those 3 parameters and hide all others. See below.

<div class="widget1 product-selector">Widget1</div> SHOW

<div class="widget2 product-selector">Widget2</div> HIDE

<div class="widget3 product-selector">Widget3</div> SHOW

<div class="widget4 product-selector">Widget4</div> SHOW

<div class="widget5 product-selector">Widget5</div> HIDE

The example on the following site achieves similar, but it will only allow for a single URL parameter: http://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/

Appreciate any solutions to help me achieve this. Thanks

Query parameter should have unique variable name. Keep only one parameter 'product' and values should be separated by some special character like pipe/comma. Try following solutions, it use one parameter.

http://localhost:8080/test.html?product=widget2,widget3

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
  .product-selector{
  display: none;
}
  </style>
</head>
<body>
  <div class="widget1 product-selector">Widget1</div>

<div class="widget2 product-selector">Widget2</div>

<div class="widget3 product-selector">Widget3</div>

<div class="widget4 product-selector">Widget4</div>

<div class="widget5 product-selector">Widget5</div>
<script>
(function() {
  function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
  }
  var products = getParameterByName('product');
  products = products.split(',');
  products.forEach((product) => {
    var el = document.getElementsByClassName(product)[0];
    el.style.display = 'block';
  });
})();
</script>
</body>
</html>

Let me know if this solve your problem.

</div>