首页 > 解决方案 > 单击按钮时无法重定向到新 URL

问题描述

我的网页中有以下内容:-

<select id="customernames">
//options goes here
</select> 
<button id="myButton" class="float-left submit-button" >Home</button>
<script>
document.getElementById("myButton").onclick = function ()
{
var siteurl = $("#customernames").val()
alert(siteurl);       
window.location.href = siteurl;
};
</script>

我想要做的是重定向到一个新的 url(新网页),当我点击一个按钮时,该 URL 将是选择列表中的一个选项值。现在目前我能够正确获取 URL 值,但是当我单击按钮时我被重定向到当前页面,所以似乎window.location.href = siteurl;会忽略siteurl并只是重定向到当前页面。所以有人可以建议吗?

标签: javascriptjqueryhtml

解决方案


click可以使用jquery事件return false来阻止表单提交

$(function() {

    $('#myButton').click(function() {
        window.location.href = $("#customernames").val();

        return false;
    });

});

或者正如@Kamae 提到的,您可以添加e.preventDefault();到您当前的功能


推荐阅读