如何通过javascript更改html输出

How to change html output through javascript?

本文关键字:html 输出 更改 javascript 何通过      更新时间:2023-11-06

如果已经有人问我这个问题,我真诚地道歉,但我对这个问题还很陌生,在网上找不到答案。。。

我正在学习如何将javascript与html结合使用,并尝试根据用户输入的内容更改html输出。类似这样的东西:

<!DOCTYPE html>
<html>
<script>
function showCost() {
    var registrationJS = document.forms["myForm"]["registration"].value;
    var adsJS = document.forms["myForm"]["ads"].value;
    var cost = 0;
    if (registrationJS == "premium") {
        cost += 50;
    }
    if (ads == "yes") {
        cost += 2;
    }
    cost = '$'+cost;
    document.write(cost);
}
</script>
<head>
</head>
<body>
<form name="myForm" method="post">
Registration:<select id="registration">
    <option value="premium">Premium</option>
    <option value="free">Free</option>
</select>
Pay to get rid of ads?<br>
<input type="radio" id="ads" value="yes">Yes<br>
<input type="radio" id="ads" value="no">No<br>
Cost: <-- display cost -->
<script>showCost(); <-- ???? --> </script>
</form>
</body>
</html>

基本上,我如何显示成本,我如何使它在每次更改输出时更新,它将显示新的成本?

顺便说一句,我知道如果我把它变成高级的,然后免费的,它就不会倒退了,我只是想了解html部分的基本知识和语法。。。谢谢!:)

制作一个div:

Cost: <div id = "cost"></div>

并且在功能而不是文档中。写(成本),做

document.getElementById('cost').innerHTML = cost;

要使用用户输入进行更新,请使用合适的事件处理程序:Events

这里有一种方法,可以使用事件侦听器。

(function(sel,inp) {
  function showCost() {
    var cost = 0;
    if (sel.value == "premium") {
      cost += 50;
    }
    if (inp[0].checked) {
      cost += 2;
    }
    cost = '$'+cost;
    document.getElementById('cost').textContent = cost;
  }
  
  showCost();
  sel.addEventListener('change', function(e) {
    showCost(e);
  })
  for (var i = 0; i < inp.length; i++) {
    inp[i].addEventListener('click', function(e) {
      showCost(e);
    })
  }
})(document.querySelector('.registration'),document.querySelectorAll('input'));
<form name="myForm" method="post">
Registration:<select class="registration">
    <option value="premium">Premium</option>
    <option selected value="free">Free</option>
</select>
<br>
Pay to get rid of ads?<br>
<input type="radio" name="ads" value="yes">Yes<br>
<input type="radio" name="ads" checked value="no">No<br>
Cost:<span id="cost"></span> 
</form>