我正在尝试通过链接将输入的文本发送到框中。请在下面查看我的代码。由于某种原因它没有通过发送吗?

<script>
    var discountCode = document.getElementById("discountCode").value;
        openPage = function() {
        location.href = "payment.php?discount="+discountCode;
    }
</script>
<a href ="javascript:openPage()" class="btn btn-warning">Purchase</a>

最佳答案

您将在页面加载后立即读取该值,而不是单击链接时。您只需要将行移动到函数中:

<script>
    openPage = function() {
        var discountCode = document.getElementById("discountCode").value;
        location.href = "payment.php?discount="+discountCode;
    }
</script>
<a href ="javascript:openPage()" class="btn btn-warning">Purchase</a>


或者,也可以在页面加载时获取对元素的引用(假设此脚本位于discountCode元素之后),然后读取函数中的值:

<script>
    var discountCode = document.getElementById("discountCode");
    openPage = function() {
        location.href = "payment.php?discount="+discountCode.value;
    }
</script>
<a href ="javascript:openPage()" class="btn btn-warning">Purchase</a>

08-04 21:39