gpt4 book ai didi

javascript - 如何限制在我的 Javascript 代码中 append ?

转载 作者:行者123 更新时间:2023-12-04 10:13:06 26 4
gpt4 key购买 nike

我 append 了一个 div,它从 switch 中检查并打印结果,但是每次我点击按钮时,它都会给我结果,我想以某种方式将结果/输出限制为 1 仅这是我的 html 代码:

<input type="text" id="input" placeholder="Name">
<button type="button" id="check_btn">Check</button>
<div id="output"></div>`

这是我的 javascript 代码:
var handle = function () {
var check = document.getElementById('input').value;
var out = document.getElementById('output');
var p = document.createElement("p");


switch(check) {
case "Rifat":
p.innerHTML = "check is Rifat";
break;
case "Sakib":
p.innerHTML = "Check is Sakib";
break;
default:
p.innerHTML = "Check Default !";
break;
}
out.append(p);

}

document.getElementById('check_btn').addEventListener("click", handle);


提前致谢。

最佳答案

覆盖输出结果。请参阅演示中的逐行注释。

// Register the change event to the <form>
document.forms.main.onchange = handler;

// Pass the event object
function handler(event) {

/*
- "this" is the <form>
- `field` is a NodeList of all inputs, outputs,
buttons, etc...
*/
const field = this.elements;

/*
event.target is always the tag that the user interacted
with.
*/
const interacted = event.target;

/*
In this case event.target is <input> because the of the
"change" event and the if condition only accepts
<input> or nothing.
*/
if (interacted.id === 'input') {

// Get the value of <input>
let check = interacted.value;

/*
- Determine result from switch outcome
- Note: the value is converted to lower case. It's just
better UX not to get user fusterated over trivial
crap
- The reply is directly overwitten to the <output> so
it doesn't pile up on the <output>
*/
switch (check.toLowerCase()) {
case "rifat":
field.output.innerHTML = "Rifat is checked.";
break;
case "sakib":
field.output.innerHTML = "Sakib is checked.";
break;
default:
field.output.innerHTML = "Nothing is checked.";
break;
}
}
}
:root,
body {
font: 400 3vw/1.5 Consolas;
}

input,
button,
output {
font: inherit;
}

#output {
color: tomato
}
<form id='main'>
<input id="input" placeholder="Name" type="text">
<button id="check" type="button">Check</button><br>
<output id="output"></output>
</form>

关于javascript - 如何限制在我的 Javascript 代码中 append ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61229810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com