我想将href属性添加到我的选择列表(CountryList)元素:
var s = document.getElementById('CountryList');
var option = document.createElement("option");
option.text = "FR";
option.value = "FR";
option.setAttribute('href', 'https://www.facebook.com/');
s.add(option);
var option2 = document.createElement("option");
option2.text = "EN";
option2.value = "US";
option2.setAttribute('href', 'https://www.facebook.com/');
s.add(option2);
var option3 = document.createElement("option");
option3.text = "AR";
option3.value = "AR";
option3.setAttribute('href', 'https://www.google.com/');
s.add(option3);
var option4 = document.createElement("option");
option4.text = "ES";
option4.value = "ES";
option4.setAttribute('href', 'https://www.yahoo.com/');
s.add(option4);
var option5 = document.createElement("option");
option5.text = "IT";
option5.value = "IT";
option5.setAttribute('href', 'https://www.youtube.com/');
s.add(option5);
当我选择一个选项时,它应该将我重定向到特定的href地址,但目前它只是将我重定向到“yahoo”和“youtube”,而其他元素不会重定向。
答案 0 :(得分:2)
定义var s=document...
后添加:
s.onchange = function() {
var sel = this.options.selectedIndex;
window.location = this.options[sel].getAttribute('href');
}
答案 1 :(得分:1)
试试这个
var s = document.getElementById('CountryList');
var option = document.createElement("option");
option.text = "FR";
option.value = "FR";
option.setAttribute('data-href','https://www.facebook.com/') ;
s.add(option);
var option2 = document.createElement("option");
option2.text = "EN";
option2.value = "US";
option2.setAttribute('data-href','https://www.facebook.com/') ;
s.add(option2);
var option3 = document.createElement("option");
option3.text = "AR";
option3.value = "AR";
option3.setAttribute('data-href','https://www.google.com/') ;
s.add(option3);
var option4 = document.createElement("option");
option4.text = "ES";
option4.value = "ES";
option4.setAttribute('data-href','https://www.yahoo.com/') ;
s.add(option4);
var option5 = document.createElement("option");
option5.text = "IT";
option5.value = "IT";
option5.setAttribute('data-href','https://www.youtube.com/') ;
s.add(option5);
function redirect(obj){
window.open(obj.selectedOptions[0].getAttribute("data-href"))
}

<select id="CountryList" onchange="redirect(this);">
<option>Select Country</option>
</select>
&#13;
答案 2 :(得分:0)
这个问题令我感到困惑,因为它被标记为jquery
,但你要避免使用很多明显的jQuery API来简化这一过程。
var countries = $('#CountryList');
countries.append([
$('<option></option>').text('FR').attr({
value: 'FR',
href: 'https://www.facebook.com/'
}),
$('<option></option>').text('EN').attr({
value: 'US',
href: 'https://www.facebook.com/'
})
])
countries.on('change', function () {
window.location = $(this).find(':selected').attr('href');
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="CountryList"></select>
&#13;