如何在js中选择具有相同类名的按钮列表中的单击按钮?
我正在使用一些 javascript 代码,并且我有一个具有相同类名的按钮列表,但我想知道单击其中的哪个按钮才能获取值。我怎样才能用 vanilla js 做到这一点?这是示例代码
<button onclick="chooseRating()" id="rateBtn" class="rateBtn" value="1">1</button>
<button onclick="chooseRating()" id="rateBtn" class="rateBtn"value="2">2</button>
<button onclick="chooseRating()" id="rateBtn" class="rateBtn"value="3">3</button>
<button onclick="chooseRating()" id="rateBtn" class="rateBtn"value="4">4</button>
<button onclick="chooseRating()" id="rateBtn" class="rateBtn"value="5">5</button>
,我尝试的js代码是
const rateBtn = document.getElementsByClassName("rateBtn");
function chooseRating() {
for (rate in rateBtn) {
console.log(rateBtn[rate]);
if (rateBtn[rate].clicked === true) {
rating = rateBtn[rate].value;
console.log(rating);
//shows 5 don't know why
}
}
}
I was working with some javascript code and i have a list of buttons with the same class names but i wanted to know which button among them is clicked inorder to get the value. How can I do that with vanilla js? Here is the sample code
<button onclick="chooseRating()" id="rateBtn" class="rateBtn" value="1">1</button>
<button onclick="chooseRating()" id="rateBtn" class="rateBtn"value="2">2</button>
<button onclick="chooseRating()" id="rateBtn" class="rateBtn"value="3">3</button>
<button onclick="chooseRating()" id="rateBtn" class="rateBtn"value="4">4</button>
<button onclick="chooseRating()" id="rateBtn" class="rateBtn"value="5">5</button>
and the js code i tried is
const rateBtn = document.getElementsByClassName("rateBtn");
function chooseRating() {
for (rate in rateBtn) {
console.log(rateBtn[rate]);
if (rateBtn[rate].clicked === true) {
rating = rateBtn[rate].value;
console.log(rating);
//shows 5 don't know why
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您首先应该为每个按钮定义一个唯一的id。
此外,您可以将 HTML 元素作为参数传递给 onClick 方法。
例如:
然后您可以从普通的 javascript 代码获取 HTML 按钮的 ID 和值:
You should first of all define a unique id per button.
Additionally, you can pass the HTML element to your onClick method as a parameter.
So for example:
You can then from vanilla javascript code get the ID and the value of your HTML button:
您只需将变量传递给每个按钮中的函数调用即可。
例子:
onclick="myFunction(variable)"
HTML 文件:
JavaScript 文件:
You can just pass on a variable to the function-call in each button.
EXAMPLE:
onclick="myFunction(variable)"
HTML-file:
JavaScript-file: