如何通过javascript更改html输出
How to change html output through javascript?
如果已经有人问我这个问题,我真诚地道歉,但我对这个问题还很陌生,在网上找不到答案。。。
我正在学习如何将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>
相关文章:
- 用Koa打印漂亮的HTML输出
- 如何在文本框中显示内部 HTML 输出
- 使用 HTML 输出标记查看可缩放图像并分配 src
- 有没有办法在使用 html 输出标签时控制图像的大小
- 我可以't从draft js中获取html输出
- 在使用append()后,美化html输出
- 使用Gulp Usemin将JS和HTML输出到不同的位置
- 使用外部JS文件对Servlet进行更改'的HTML输出
- 如何通过javascript更改html输出
- 你如何为 HTML 输出编写测试用例
- 奇怪的 HTML 输出
- AngularJS:将HTML输出写入文本文件
- 不知道如何使用 ajax 将 html 输出到页面上
- 在文本区域而不是 HTML 代码中显示 HTML 输出
- 请求 JSONP 时的文本/html 输出
- 表单提交时的 HTML 输出更新
- 余烬.js HTML 输出损坏
- 谷歌网络应用程序加载脚本不适用于HTML输出
- 使用 JavaScript 对 HTML 输出 (ASP.Net) 所做的更改立即撤消
- HTML-输出文本的元素