我正在尝试通过链接将输入的文本发送到框中。请参阅下面的代码。它出于某种原因没有通过?
<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>
答案 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>