无法在锚点内设置跨度的内容

Can't set a span's content within an anchor

我有这个字段。

<input type="text" name="amount" id="amount" value="20.00">

我有这个link。

<a target='_blank' href="https://PayPal.me/MyAccount/<span id='myspan'>0.00</span>">click here</a>

当我尝试将金额值 ($20.00) 插入 myspan 时,出现此错误: "Uncaught TypeError: Cannot set property 'innerHTML' of null"

我正在使用文件底部的 Javascript。

    <script type ="text/javascript">
    window.addEventListener('load', function () {
      myFunction();
    })

    function myFunction() {
     var thisamount = document.getElementById("cart_total").value;
     alert(thisamount);
     document.getElementById("myspan").innerHTML = thisamount;
    }
    </script>           

我到底做错了什么?

你的锚应该是这样的
<a target='_blank' id="myHref" href="#"><span id='myspan'>0.00</span>USD</a>

然后

function myFunction() {
     var thisamount = document.getElementById("cart_total").value;
     alert(thisamount);
     document.getElementById("myHref").href = `https://PayPal.me/MyAccount/${thisamount}`;
     document.getElementById("myspan").innerHTML = thisamount;
    }
  1. 您引用了 cart_total 但您的字段名为 amount
  2. 引号内的跨度是文本节点的一部分,它不再是单独的 DOM 节点

    window.addEventListener('load', function () {
        myFunction();
    });

    function myFunction() {
        var thisamount = document.getElementById("amount").value;
        console.log("thisamount", thisamount);
        let url = `https://PayPal.me/MyAccount/${thisamount}usd`;
        console.log("url", url);
        document.getElementById("paypalLink").setAttribute("href", url);
    }
<input type="text" name="amount" id="amount" value=".00">
<a id="paypalLink" target='_blank' href="https://PayPal.me/MyAccount/">Pay Me!</a>

  1. 调用前首先要声明函数

       <script type ="text/javascript">
        function myFunction() {
         var thisamount = document.getElementById("cart_total").value;
         alert(thisamount);
         document.getElementById("myspan").innerHTML = thisamount;
        }
    
       window.addEventListener('load', function () {
        myFunction();
       })
      </script>
    
  2. 你不能在另一个元素属性中添加一个元素

    <a target='_blank' href="https://PayPal.me/MyAccount">
    <span id='myspan'>0.00</span>
    

另一种解决方案可能是这样的(我在代码片段中做了注释):

document.querySelector('#amount').addEventListener('change', function() { // add change event to the input in order to update the current href
    document.querySelector('#sendMoney').setAttribute('href', 'https://PayPal.me/MyAccount/'+this.value+'USD'); // set the href 
    document.querySelector('#sendMoney').textContent = this.value+'$'; // set text content with current value
});
<label for="amount">Set amount</label>
<input type="number" name="amount" id="amount" value="20.00" />
<br />
<a id="sendMoney" href="https://PayPal.me/MyAccount/" target="_blank"></a>