使用javascript预选择基于URL的值

时间:2018-08-28 02:32:36

标签: javascript

我目前正在一个网站上工作,该网站的搜索引擎包括带有过滤器的高级搜索选项。我希望选择基于URL的类别,以便显示相关的过滤器。例如,如果访问者位于domain.com/category/adventure,则将类别预先选择为“冒险”。我不确定如何读取网址。

<script>

var mainCat = document.getElementById("main_cat")
var customFields = document.getElementById("custom_fields")

// When the website first loads, hide "custom_fields" by default
customFields.style.display = "none";

// When the user changes the main_cat select, check it's value. If
// value == "-1" then hide custom_fields. Otherwise display custom
// fields as inline
mainCat.addEventListener("change", function() {

if (mainCat.value == "-1") 
{
  customFields.style.display = "none";
}
else
{
  customFields.style.display = "inline";
}

})

</script>

mainCat的可能值包括:冒险,烹饪,一日游等。我希望根据url(domain.com/category/adventure ... domain.com/category/culinary ..)选择这些值。 customFields是div容器的ID,该容器显示所有包含php生成的内容的过滤器。 mainCat是类别的ID,如果值为-1,则不会选择任何类别。

2 个答案:

答案 0 :(得分:2)

要预先选择<select>元素的类别,可以从当前浏览器的location(包含URL)中提取类别,然后更新{{1} }元素:

<select>

更新

基于网站的CSS和DOM结构,对代码的这些调整应可以满足您的要求:

<script>

  var mainCat = document.getElementById("main_cat")
  var customFields = document.getElementById("custom_fields")

  // When the website first loads, hide "custom_fields" by default
  customFields.style.display = "none";

  // When the user changes the main_cat select, check it's value. If
  // value == "-1" then hide custom_fields. Otherwise display custom
  // fields as inline
  mainCat.addEventListener("change", function() {

  if (mainCat.value == "-1") 
  {
    customFields.style.display = "none";
  }
  else
  {
    customFields.style.display = "inline";
  }

  })

  //[ADDED]

  // Extract category from current url
  const category = location.pathname
  .split('/') // Break pathname to array of strings, split by '/' characters
  .filter(function(item) { return !!item; }) // Remove any empty strings from array
  .splice(-1); // Get last string (your category) from array

  // Update value of select element to current category
  document.getElementById("main_cat").value = category;

</script>

答案 1 :(得分:0)

使用window.location:

console.log(window.location.pathname);

然后可以通过分割/字符来分割路径,然后在遍历路径元素时填充字段。