我正在尝试通过链接将输入的文本发送到框中。请参阅下面我的代码。由于某种原因没有发送出去?
<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>
关于javascript - 使用 Javascript 通过链接抓取并发送文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33258818/