Javascript排序在Firefox中有效,但在Chrome中不起作用。只需执行简单的Select操作即可将用户带到新的网址。我可以进行哪些修改才能使其在所有浏览器上都能正常工作?

Stackoverflow说我需要更多说明文字。尽管我认为这是一个相当简单的问题。用户选择一个选项,并定向到新的URL。该代码在Firefox中重定向,但在Chrome中不重定向。我尚未检查其他浏览器。



function url() {
  var value1 = $("#sort").val();
  var currentURL = window.location.href;

  if (window.location.href.endsWith("/")) {
    var str1 = (currentURL + '?');
  } else if (window.location.href.includes('&orderby')) {
    var str1 = (currentURL.split('&orderby')[0] + '&');

  } else if (window.location.href.includes('?orderby')) {
    var str1 = (currentURL.split('?orderby')[0] + '?');

  } else {
    var str1 = (currentURL + '&');
  }


  if (value1 == 'sort1') {
    window.location.href = str1 + "orderby=date&order=dsc";
  }
  if (value1 == 'sort3') {
    window.location.href = str1 + "orderby=date&order=asc";
  }
  if (value1 == 'sort5') {
    window.location.href = str1 + "orderby=title&order=dsc";
  }
  if (value1 == 'sort7') {
    window.location.href = str1 + "orderby=title&order=asc";
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sort" class="sorts2">
  <option class="sorts-option" value="">Sort</option>
  <option class="sorts-option" value="sort1" onclick="url()">Latest</option>
  <option class="sorts-option" value="sort3" onclick="url()">Oldest</option>
  <option class="sorts-option" value="sort5" onclick="url()">Title DSC</option>
  <option class="sorts-option" value="sort7" onclick="url()">Title ASC</option>
</select>

最佳答案

您必须对select标签执行onchange而不是对选项标签执行onclick。 (由于select是实际的输入控件,因此您只需将事件绑定到select标记。

像这样



function url() {
  var value1 = $("#sort").val();
  var currentURL = window.location.href;

  if (window.location.href.endsWith("/")) {
    var str1 = (currentURL + '?');
  } else if (window.location.href.includes('&orderby')) {
    var str1 = (currentURL.split('&orderby')[0] + '&');

  } else if (window.location.href.includes('?orderby')) {
    var str1 = (currentURL.split('?orderby')[0] + '?');

  } else {
    var str1 = (currentURL + '&');
  }


  if (value1 == 'sort1') {
    window.location.href = str1 + "orderby=date&order=dsc";
  }
  if (value1 == 'sort3') {
    window.location.href = str1 + "orderby=date&order=asc";
  }
  if (value1 == 'sort5') {
    window.location.href = str1 + "orderby=title&order=dsc";
  }
  if (value1 == 'sort7') {
    window.location.href = str1 + "orderby=title&order=asc";
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sort" class="sorts2" onchange="url()">
  <option class="sorts-option" value="">Sort</option>
  <option class="sorts-option" value="sort1" >Latest</option>
  <option class="sorts-option" value="sort3" >Oldest</option>
  <option class="sorts-option" value="sort5" >Title DSC</option>
  <option class="sorts-option" value="sort7" >Title ASC</option>
</select>

09-25 16:31