当使用javascript和html时,span标签不起作用

问题描述 投票:-1回答:3

我正在尝试制作一个程序,该程序先计算一些东西,然后将其结果打印在一行的中间,这就是为什么要使用跨度的原因。因此,我尝试了几种方法,可以在文本输入中打印结果,但不能在跨度中打印结果。如您在此代码中所见。

<script>
function calculate() {
    //these first two variables are the ones we use to calculate and the third is for saving 
      the calculation
    var 1 = parseFloat(document.getElementById("1a").value);
    var 2 = parseFloat(document.getElementById("2a").value);
    var 3 = parseFloat(document.getElementById("3a").value = 1 * 2);
}
</script>
 <!-- in this tag I aks the user to give two variables -->
 <p style="line-height:1.4">
    give number 1 & 2:
    <input type="text" name="1b" id="1a"/>
    x
    <input type="text" name="2b" id="2a"/>
    <br/>
</p>
<p style="line-height:1.4">
    <input type="button" value="calculate" onClick="calculate();"/>
    <br/>
</p>
<!--in this tag I print the result but in the span it doesn't work while the text input does print 
  the result -->
<p> 
    <input type="text" name="3b" id="3a"/>
    The result is <span id="3a"></span>. 
</p>

有人知道如何解决此问题吗?

javascript html
3个回答
0
投票

一个元素的ID在所有其他元素中应该是唯一的,以便有效地工作。在发布的代码中,您拥有与2个不同元素相关联的ID“ 3”。这将导致意外的行为,因为当请求ID为'3'的元素时,浏览器的DOM API可能只是返回第一个匹配的元素。要使其正常工作,请为输入和跨度指定两个其他所有元素唯一的不同ID []


0
投票

innerHTML用于非格式元素:


0
投票

为了在span标签中打印结果,您必须使用innerText而不是value:

© www.soinside.com 2019 - 2024. All rights reserved.