Kas*_*ras 0 html javascript if-statement ejs
您好,我是 HTML 和 JS 新手,因此想寻求一些帮助。这里我想根据 if 语句为 true 或 false 显示两个不同的 HTML 元素。然而,它不起作用。我可以寻求帮助吗?(:
<!DOCTYPE html>
<html>
<body>
<script>
if (!user) {
<h1> there is no user </h1>
} </script>
if (user) {
<button type="button">Click Me!</button>
} </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是一个原生的 Javascript 替代方案
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<script>
var el = document.getElementById('content');
var content;
if (!user) {
content = '<h1>there is no user</h1>';
}
if (user) {
content = '<button type="button">Click Me!</button>';
}
el.insertAdjacentHTML('afterbegin', content);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
不过,除非定义了变量,否则这不会按原样工作user
,但我假设您已经在运行时使用了它。
如果您在此 div 中有更多 html,则可以使用不同的插入位置,请参阅此处的相关文档:https: //developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML