我有一个问题与我的onclick函数在JavaScript



<html>
<head><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.css">
<link rel="stylesheet" href="index.css">
</head>
<body>
<img src="images/shoe.jpeg" alt="Nike shoe">
<p>Nike shoe</p>
<button>Purchase - $149</button>
<p id="error" onclick="purchase()"></p>
<script>
// When the user clicks the purchase button, render out
// "Something went wrong, please try again" in the paragraph
// that has the id="error".

let errorID = document.getElementById("error")
console.log(errorID)
function purchase() {
console.log("Button is clicked")
errorID.textContent =  "Something went wrong, please try again"
}

</script>
</body>
</html>

因此,当按钮被点击时,它应该在javascript中所述的p标签内呈现错误消息。我甚至正确地抓取了id,并正确地陈述了一切,但它不起作用。我似乎找不到问题

当我想点击一个按钮,它不工作

你的onclick需要在按钮上,而不是p

let errorID = document.getElementById("error")
console.log(errorID)
function purchase() {
console.log("Button is clicked")
errorID.textContent =  "Something went wrong, please try again"
}
<button onclick="purchase()">Purchase - $149</button>
<p id="error"></p>

Nike鞋

购买- $149
// When the user clicks the purchase button, render out
// "Something went wrong, please try again" in the paragraph
// that has the id="error".

let errorID = document.getElementById("error")
console.log(errorID)
function purchase() {
console.log("Button is clicked")
errorID.textContent =  "Something went wrong, please try again"
}

</script>
</body>

正确代码是这样的,请参阅语法call onclick on button

最新更新