我的两个js函数分开工作,但不一起工作



所以我尝试创建一个函数来清除屏幕并根据我按下的按钮向我发送警报。我可以毫无问题地清除屏幕并收到警报,但我似乎无法通过按一下按钮来使两者发生。

<head>
<script>
function cleartext() {
document.getElementById("text0").style.display = "none";
}   
function btnchecklist() {
document.getElementById("btn1").onclick = function() {
alert("hello1");
}
document.getElementById("btn2").onclick = function() {
alert("hello2");
}
document.getElementById("btn3").onclick = function() {
alert("hello3");
}
}       
</script>
</head>
<body>
<div id="text0"> 
<p> some text </p>
</div>     
<div id="btn-group">
<button id="btn1" onclick="cleartext(); btnchecklist();"> 1 </button>
<button id="btn2" onclick="cleartext(); btnchecklist();"> 2 </button>
<button id="btn3" onclick="cleartext(); btnchecklist();"> 3 </button>    
</div>    
</body>     

在下面查看我的答案 这不是最好的解决方案,如果你向我解释你想做什么,可能是我提供一个更干净的答案。

So I have tried to create a function that clears the screen and sends me an alert based on what button I have pressed. I
can clear the screen without any problems and also receive the alert but I can't seem to make both happen with one press
of a button.
<head>
<script>
function cleartext() {
document.getElementById("text0").style.display = "none";
}
window.onload = function () {
document.getElementById("btn1").onclick = function () {
alert("hello1");
cleartext();
}
document.getElementById("btn2").onclick = function () {
alert("hello2");
cleartext();
}
document.getElementById("btn3").onclick = function () {
alert("hello3");
cleartext();
}
};  
</script>
</head>
<body>
<div id="text0">
<p> some text </p>
</div>
<div id="btn-group">
<button id="btn1"> 1 </button>
<button id="btn2"> 2 </button>
<button id="btn3"> 3 </button>
</div>
</body>

最好使用此代码。

将按钮元素传递给您的 btnchecklist 函数 (this(,并在您的函数中获取已传递元素的 id,并使用相应的文本显示警报。

function cleartext() {
document.getElementById("text0").style.display = "none";
}
function btnchecklist(element) {
//Read id of element
switch (el.id) {
case "btn1":
alert("hello1"); //Output in case of element id is btn1
break;
case "btn2":
alert("hello2");
break;
case "btn3":
alert("hello3");
break;
}
}
<div id="text0">
<p> some text </p>
</div>
<div id="btn-group">
<!-- Pass element to your btnchecklist function (this) -->
<button id="btn1" onclick="cleartext();btnchecklist(this)"> 1 </button>
<button id="btn2" onclick="cleartext();btnchecklist(this)"> 2 </button>
<button id="btn3" onclick="cleartext();btnchecklist(this)"> 3 </button>
</div>

更短但更复杂的代码是:

var aButtons = document.querySelectorAll("#btn-group>button"); //Get all buttons in btn-group
aButtons.forEach(function(oButton){ //Loop buttons
oButton.addEventListener("click", function(el){ //Add click event listener to each button
var regex = new RegExp(/([d+])/); //Regulr Expression to find the number in your bvutton id
document.getElementById("text0").style.display = "none";
alert("hello" + el.target.id.match(regex)[0]); //Alert "hello" Text + number in your button id
});
});

最新更新