新手问题:
在 jQuery 中,我如何让浏览器导航到选定的饮料?
<select name="selDrink" id="selDrink">
<option value="http://coke.com">Coke</option>
<option value="http://pepsi.com">Pepsi</option>
</select>
最佳答案
//select the element and bind a `change` event handler to it
$('#selDrink').on('change', function () {
//redirect the user to the value of the select element
window.location = this.value;
});
您可能想要一个空白 <option>
在顶部所以所有 <option>
s 与实际 value
s 是可选的:
HTML --
<select name="selDrink" id="selDrink">
<option value="">Choose One</option>
<option value="http://coke.com">Coke</option>
<option value="http://pepsi.com">Pepsi</option>
</select>
JS --
$('#selDrink').on('change', function () {
//check if the selected value of this element is blank, if not then redirect to the value
if (this.value != '') {
window.location = this.value;
}
});
请注意.on()
是 jQuery 1.7 中的新增内容,在本例中使用类似 .bind()
.
这是一个演示:http://jsfiddle.net/Duanx/
window.location
的文档: https://developer.mozilla.org/en/DOM/window.location
关于jQuery:根据选定的 <Option> 进行导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9118440/