我正在尝试向dropdron菜单添加超链接。菜单是动态创建的,但最后一个选项值和文本始终是“添加新作业”。我希望在用户单击该选项时重定向页面。我有谷歌,但尚未找到一个好的解决方案。
<select name='job'>
<option value='value1'>value1</option>
<option value='value2'>value2</option>
<option value='value3'>value3</option>
//the above data are generated by server-side code.
<option value='www.sample.com'>add new job</option>
//I want the page to be redirected to the sample.com when user click the option.
</select>
答案 0 :(得分:2)
可能是这样的:
jQuery.change('select[name=job]', function() {
if ($(this).val() == "www.sample.com"){
window.location.href = "www.sample.com";
}
}
答案 1 :(得分:1)
你必须使用JavaScript。您更有可能想要捕获下拉列表的更改事件,然后检查该值是否为链接并将用户重定向到该地址。至少这是一种做法。
答案 2 :(得分:1)
<select name='job' id='job'>
<option value='value1'>value1</option>
<option value='value2'>value2</option>
<option value='value3'>value3</option>
//the above data are generated by server-side code.
<option value='goto-new'>add new job</option>
//I want the page to be redirected to the sample.com when user click the option.
</select>
$('#job').on('change', function(e) {
if ($this.val() == 'goto-new') {
// put your redirection here
window.location.href = "http://stackoverflow.com";
}
});
答案 3 :(得分:1)
实施点击处理程序并检查选择选项的值并重定向,
尝试,
$(document).ready(function() {
$('select[name="job"]').change(function() {
var selectedVal = $(this).val();
if (isValidURL(selectedVal)) {
window.location.href = selectedVal;
}
});
//Below function is copied from http://stackoverflow.com/a/9350644/297641
function isValidURL(value) {
return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7F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