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

时间:2016-06-20 22:54:42

标签: javascript html attributes

我试图将一个变量从JavaScript传递给select标签的value属性。这是我的代码: &LT;脚本&GT;  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); &LT; /脚本&GT; &lt; select OnChange =“window.location.href = this.value”&gt;    &lt; option&gt; Tagged Stuff and Navigation&lt; / option&gt;    &lt; option value = HOME_VAR&gt;主页&lt; /选项&gt; &LT; /选择&GT;

3 个答案:

答案 0 :(得分:1)

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

<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>

答案 1 :(得分:1)

如果您在javascript中添加SELECT后可以实现此目的:

<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/

答案 2 :(得分:0)

你在寻找像

这样的东西吗?
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>