【问题标题】:How to select the value in option if option value has slash如果选项值有斜线,如何选择选项中的值
【发布时间】:2018-10-12 03:58:43
【问题描述】:

HTML 选择代码

<select name="about" class="form-control radius0 clear-value" 
   id="aboutus" 
   onchange="this.options[this.selectedIndex].value && 
   (window.location = 
   this.options[this.selectedIndex].value);">
   <option value="aims-objective">AIMS &amp; OBJECTIVES</option>
   <option value="history">HISTORY</option>
   <option value="our-supporters">OUR SUPPORTERS</option>
   <option value="donate-now">DONATE NOW</option>
</select>

如果选项值是这样的,它会选取该值并显示在下拉列表中。但是现在选项值变成了

<option value="/about-us/aims-objective">AIMS &amp; OBJECTIVES</option>
<option value="/about-us/history">HISTORY</option>
<option value="/about-us/our-supporters">OUR SUPPORTERS</option>
<option value="/about-us/donate-now">DONATE NOW</option>

功能

$(function(){ // Makes current value as default one
  var selectedValue = window.location.href.substring(window.location.href.lastIndexOf('/') + 1);
  console.log(selectedValue);
  $("#aboutus").val(selectedValue);
})

现在不行了。在 onchange 函数中可能进行哪些更改。提前致谢!

【问题讨论】:

  • 分享你onchange的功能。
  • @FarhanTahir 他确实分享了这个功能,是内联编码的
  • 我的坏人刚刚看到了。谢谢。
  • 它对我有用吗? jsfiddle.net/qpkdLmqt
  • @monisha ,我很确定不是带有斜线的选项导致了问题,可能是 url 值导致它,尝试value="./about-us/history"

标签: javascript


【解决方案1】:

请检查我的答案,我假设您在 abc.test/about-us/history 页面并运行代码并检查,HISTORY 将是 preselected

由于site url 不会更改,您可以遵循此解决方案。

// script to chnage the dropdown

function selectChange(select){ 
var selectedValue; 
if(select != undefined){ 
selectedValue = select.options[select.selectedIndex].value; 

selectedValue = '/about-us/' + selectedValue; 
select.options[select.selectedIndex].value = selectedValue; 
$("#aboutus").val(selectedValue); 
window.location = selectedValue; 
} 
else{ 
selectedValue = window.location.href.substring(window.location.href.lastIndexOf('/') + 1); 
} 
console.log(selectedValue); 
$("#aboutus").val(selectedValue); 
} 

selectChange(); 

// script to pre select the dropdown

$(function(){ 
console.log(window.location.href); 
var selectedValue = window.location.href.substring(window.location.href.lastIndexOf('/') + 1); 
console.log(selectedValue); 
$("#aboutus").val(selectedValue); 
})
<div class="col-md-3 desktop styled-select"> 
<select name="about" class="form-control radius0 clear-value" id="aboutus" onchange="selectChange(this)"> 
<option value="aims-objective">AIMS &amp; OBJECTIVES</option> 
<option value="history">HISTORY</option> 
</select> 
</div>

Here is a Working DEMO

【讨论】:

  • @monisha,请检查我的回答,如果您需要任何更改,请告诉我
  • 有一个站点 abc.test,当涉及到 abc.test/about-us 时,有一个下拉列表,该下拉列表会更改 URL 并转到其他页面,例如是否选择了历史记录页面并且 URL 更改为 abc.test/about-us/aims-objective 并且选择值为 AIMS $amp;目标
  • 您为每个页面添加的脚本都加载了吗?
  • 你能把console.log(selectedValue);的结果发过来吗
  • 我们的支持者,历史,现在捐赠..选择哪个
猜你喜欢
  • 1970-01-01
  • 2020-03-03
  • 2019-09-05
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2015-07-08
相关资源
最近更新 更多