使用Javascript通过链接抓取并发送文本值

时间:2015-10-21 12:03:29

标签: javascript

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

<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>

1 个答案:

答案 0 :(得分:1)

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

<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>