web3.js调用问题

在学习web3.js,想用html显示查询地址的余额,点击按钮时,发现js可以查看到余额,但是并不能赋值给html的元素,请问怎么改?

<!DOCTYPE html>
<html>
    <head>
        <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.3.0/web3.min.js"></script>
        <title>view your balance</title>
        <style>
            input[type=text], select {
                width: 100%;
                padding: 12px 20px;
                margin: 8px 0;
                display: inline-block;
                border: 1px solid #ccc;
                border-radius: 4px;
                box-sizing: border-box;
            }
            button[type=button] {
                width: 100%;
                background-color: #4CAF50;
                color: white;
                padding: 14px 20px;
                margin: 8px 0;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                }
            div {
                width: 300px;
                border-radius: 5px;
                background-color: #f2f2f2;

            }
        </style>
        <script>

        </script>
    </head>
    <body>
        <h3>查看你的钱包余额</h3>
        <div>
            <form>
              <label for="title">My Balance</label>
              <input type="text" id="address" name="address" placeholder="Your address..">     
              <button id="getBalance" type="button" onclick="myBalance()">getBalance</button>
              <h3 id="thebalance">0</h3>  
            </form>
          </div>
          <script> 

            function myBalance(){
            var infuraUrl = "https://kovan.infura.io/v3/6185543f1415428fb08d15c08ec22c2c"
            var privateKey = "03c6cd272dd6e913ca6bd9501f37dac27f4deb0262711d9af589beb15a1c0c8a"
            var web3 = new Web3(infuraUrl)
            var account = web3.eth.accounts.privateKeyToAccount(privateKey)
            web3.eth.defaultChain = 'Kovan'
            var fromAddr = account.address
            var fromAddr1 = document.getElementById("address").value;
            web3.eth.getBalance(fromAddr1).then(console.log)
            web3.eth.getBalance("fromAddr1").then(function(balance){document.getElementById("thebalance").innerHTML =  balance;
});          
            }
        </script> 
     </body>

</html>

image.png

请先 登录 后评论

1 个回答

Tiny熊
  擅长:智能合约,以太坊
请先 登录 后评论
  • 1 关注
  • 0 收藏,2775 浏览
  • zhou 提出于 2020-12-03 22:51