qfedu-web/www/js4.html

38 lines
1.3 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="author" content="flykhan" />
<meta name="keywords" content="c c++ 物联网" />
<title>JS分支与循环语句</title>
</head>
<body>
<label>请输入一个整数:</label>
<!-- input 的 onchange 表示输入数据之后回车,则调用的时间处理函数 -->
<input placeholder="建议大于10的整数" onchange="handler1(this)" />
<h3>输入的整数以内所有偶数和:</h3>
<div id="ret"></div>
<script>
function handler1(input_element) {
let n = parseInt(input_element.value); // 将字符串转换为整数
console.log(input_element.value);
input_element.value = ""; // 清空输入框的内容
let sum_ = 0;
for (let i = 2; i <= n; i++) {
if (i % 2 == 0) {
sum_ += i;
}
}
// 通过标签的 id 属性获取元素(浏览器会自动将 id 属性的值作为一个变量名)
// 通过 id 获取元素
let ret = document.getElementById("ret");
// ret.innerText = "" 显示纯文本不渲染HTML标签
// ret.innerHTML = "" 显示HTML标签渲染HTML标签
ret.innerHTML = "<b style='color: red;'>" + sum_ + "</b>";
}
</script>
</body>
</html>