使用js函数动态替换div内容

时间:2016-03-13 13:11:01

标签: javascript html

好的,所以在我的功能的底部应该更新我的div告诉用户他们的BMI是什么。

这是我试图这样做的功能。

    function calcbmi(){

    //window.alert("hello");

    var weightvalue = document.getElementsByName('weight_pounds')[0].value;
    var weight = parseInt(weightvalue, 10)*0.453592;
    var height1value = document.getElementsByName('height_feet')[0].value;
    var height1 = parseInt(height1value, 10)*12;    
    var height2value = document.getElementsByName('height_inches')[0].value;
    var height2 = parseInt(height2value, 10);

    var height = (height1+height2) * 0.0254;

    //window.alert("Meters:" + height + "KG:" + weight);

    var bmi = Math.floor((weight/(height*height))); 

    //window.alert("your BMI is: " + bmi);

    var bmi = Math.floor((weight/(height*height))); 

    var container = document.getElementById("bmiinfo");
    container.innerHTML = bmi;


}

这是相应的HTML ...

  <td colspan="2"><div style="float:left;"><button onclick="calcbmi()">Calculate BMI</button></div> <div style="float:right;"><span class="hidemobile"></span>.</div><div style="clear:both;"></div></td>
            </tr>
        </table>
        </form> 
    </div>
    <div id="userbmi">
        <h1>BMI is: <span id="bmi"></spam></h1>
    </div>  

我错过了什么吗?这不起作用。

@EDIT:控制台没有错误......

1 个答案:

答案 0 :(得分:4)

更新 :(查看网页后)

替换<button onclick="calcbmi()">Calculate BMI</button>

<input onclick="calcbmi()" type="button" value="Calculate BMI"></input>

原因是按钮标记默认为表单提交,因此会调用calcbmi,但页面会立即刷新,因为它不明显。

上一个答案

修改你的html,如下所示,并添加一个span,然后将值写入其中。

<h1>BMI is: <span id="bmi"></span></h1>

这是一个工作代码段

function calcbmi (){
    var weightvalue = document.getElementsByName('weight_pounds')[0].value;
    var weight = parseInt(weightvalue, 10)*0.453592;
    var height1value = document.getElementsByName('height_feet')[0].value;
    var height1 = parseInt(height1value, 10)*12;    
    var height2value = document.getElementsByName('height_inches')[0].value;
    var height2 = parseInt(height2value, 10);

    var height = (height1+height2) * 0.0254;

    var bmi = Math.floor((weight/(height*height))); 

    var bmi = Math.floor((weight/(height*height))); 

    var container = document.getElementById("bmi");
    container.innerHTML = bmi;

}
<div>
  Weight: <input type="text" name="weight_pounds" value=""><br/>
  Height (ft): <input type="text" name="height_feet" value=""><br/>
  Height (in): <input type="text" name="height_inches" value=""><br/>
</div>

<input type="button" onclick="calcbmi()" value="Calculate" />

<div id="bmiinfo">
  <h1>BMI is: <span id="bmi"></span></h1>
</div>