将 JavaScript 变量传递给 html <select> 属性



我试图将一个变量从javascript传递到选择标签的值属性。这是我的代码:

<script>
 if (window.location.href.substring(0, 9) === "http://ww") {
     var home_var = "bing.com";
     var home_var = "poem.com";
 } else if (window.location.href.substring(0, 9) === "https://p") {
     var home_var = "https://px.multiscreensite.com/index.php?url=bing.com";
     var poem_var = "https://px.multiscreensite.com/index.php?url=poem.com";
 } else {
     var home_var = "1";
     var_poem_var = "2";
 }
 console.log(home_var);
</script>
<select OnChange="window.location.href=this.value">
   <option>Tagged Stuff and Navigation</option>
   <option value=HOME_VAR>Home Page</option>
</select>

如果在JavaScript中添加选择后,可以实现此处:

<select id="mySelect" OnChange="window.location.href=this.value">
    <option>Tagged Stuff and Navigation</option>
</select>
<script>
    if (window.location.href.substring(0,9) === "http://ww") {
    var home_var = "bing.com";    
    }
    else if (window.location.href.substring(0,9) === "https://p") {
    var home_var = "https://px.multiscreensite.com/index.php?url=bing.com";
    }
    else {
    var home_var = "1";
    }
    var select= document.getElementById("mySelect");
    var option = document.createElement("option");
    option.text = "Hope Page";
    option.value = home_var;
    select.add(option);
    console.log(home_var);
</script>

JS小提琴https://jsfiddle.net/emfvyhq2/

您可以动态添加元素...

<script>
(function() {
    var s = document.getElementById("selector");
    var o = document.createElement("option");
    o.innerHTML = "Home Page";
    o.value = home_var;
    s.appendChild(o);
})();
</script>
<select id="selector" OnChange="window.location.href=this.value">    
    <option>Tagged Stuff and Navigation</option> 
</select>

您是否正在寻找

之类的东西
function changeLink(val) {
   if(val === 'HOME_VAR'){
     ... your code logic ...
   }
}
 <select onchange="javascript:changeLink(this.value)">
       <option>Tagged Stuff and Navigation</option>
       <option value="HOME_VAR">Home Page</option>
 </select>

最新更新