问题描述
我正在尝试使用表单中的输入来创建Metamask事务的详细信息,采用表单地址和以太坊金额,然后使用Metamask对其进行调用。当用地址和数量进行硬编码时,元掩码代码才能起作用。不知道我要去哪里错了。
运行npx服务是因为Metamask可能很棘手。
感谢您的帮助!
编辑-尝试了一些新内容,但仍然无法正常工作
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div>
<input onclick="fill_amount" id="amount" type="number" placeholder="eth">
<input onclick="fill_address" id="address" placeholder="address">
<button class="pay-button">Pay</button>
<div id="status"></div>
</div>
<script type="text/javascript">
window.addEventListener('load',async () => {
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
await ethereum.enable();
initPayButton()
} catch (err) {
$('#status').html('User denied account access',err)
}
} else if (window.web3) {
window.web3 = new Web3(web3.currentProvider)
initPayButton()
} else {
$('#status').html('No Metamask (or other Web3 Provider) installed')
}
})
const initPayButton = () => {
$('.pay-button').click(() => {
// paymentAddress is where funds will be send to
var paymentAddress = document.getElementById("address").innerHTML
var amountEth = document.getElementById("amount").innerHTML
web3.eth.sendTransaction({
to: paymentAddress,value: web3.toWei(amountEth,'ether')
},(err,transactionId) => {
if (err) {
console.log('Payment Failed',err)
$('#status').html('Payment Failed')
} else {
console.log('Payment successful',transactionId)
$('#status').html('Payment successful')
}
})
})
}
function fill_amount() {
var amountEth = document.getElementById("amount").innerHTML
}
function fill_address() {
var paymentAddress = document.getElementById("address").innerHTML
}
</script>
</body>
</html>
解决方法
在您的fill_amount和fill_address函数中,您使用相同的付款地址变量。我相信在fill_amount函数内部,变量应为amountEth而不是paymentAddress。