在网页上显示逻辑操作结果
在这一步中,你将结合所学的所有逻辑运算符,创建一个综合演示,并在网页上显示结果。我们将修改 HTML 文件,以更结构化的方式展示逻辑运算符的结果。
使用以下完整代码更新 logical-operators.html
文件:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>JavaScript Logical Operators Demo</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.result {
margin: 10px 0;
padding: 10px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<h1>JavaScript 逻辑运算符探索</h1>
<div id="andResults" class="result">
<h2>AND (&&) 运算符结果</h2>
</div>
<div id="orResults" class="result">
<h2>OR (||) 运算符结果</h2>
</div>
<div id="notResults" class="result">
<h2>NOT (!) 运算符结果</h2>
</div>
<script>
// Function to display results
function displayResult(elementId, message) {
const element = document.getElementById(elementId);
const resultLine = document.createElement("p");
resultLine.textContent = message;
element.appendChild(resultLine);
}
// AND (&&) Operator Demonstration
function demonstrateAndOperator() {
let isAdult = true;
let hasLicense = true;
let canDrive = isAdult && hasLicense;
displayResult("andResults", `Can drive? ${canDrive}`);
let age = 25;
let hasValidLicense = age >= 18 && age <= 65;
displayResult("andResults", `Valid driving age? ${hasValidLicense}`);
}
// OR (||) Operator Demonstration
function demonstrateOrOperator() {
let isWeekend = false;
let isHoliday = true;
let canRelax = isWeekend || isHoliday;
displayResult("orResults", `Can relax? ${canRelax}`);
let age = 16;
let hasParentalConsent = true;
let canAttendEvent = age >= 18 || hasParentalConsent;
displayResult("orResults", `Can attend event? ${canAttendEvent}`);
}
// NOT (!) Operator Demonstration
function demonstrateNotOperator() {
let isRaining = false;
let isSunny = !isRaining;
displayResult("notResults", `Is it sunny? ${isSunny}`);
let age = 16;
let isAdult = !(age < 18);
displayResult("notResults", `Is an adult? ${isAdult}`);
}
// Run all demonstrations when page loads
function runAllDemonstrations() {
demonstrateAndOperator();
demonstrateOrOperator();
demonstrateNotOperator();
}
// Call the main function when the page loads
window.onload = runAllDemonstrations;
</script>
</body>
</html>
此版本的关键改进:
- 为每个逻辑运算符添加了样式化的结果部分
- 创建了
displayResult()
函数来显示结果
- 实现了
runAllDemonstrations()
函数以执行所有运算符演示
- 添加了基本 CSS 以提高可读性
- 使用
window.onload
确保所有脚本在页面加载后运行
示例浏览器输出将分别在样式化的部分中显示 AND、OR 和 NOT 运算符的结果。