JavaScript按钮返回错误警报 [英] JavaScript buttons returning wrong alert
问题描述
我正在申请一份工作,他们提出了一个JS问题,详情如下:
I'm applying for a job and they threw a JS question detailed below:
编写一个函数以在页面上呈现10个<button>
元素(编号从1到10),并在单击一个按钮时提醒所选按钮的编号. 不要使用jQuery或其他任何库.
Write a function to render 10 <button>
elements on the page, numbered 1 through 10, and alert the number of the chosen button when one is clicked. Do not use jQuery or any other libraries.
似乎很容易.我建立了一个工作模型,只是它会警告错误的号码.它会针对所有按钮向按钮11发出警报.我知道我忘记了一些简单的事情.以下是我的代码(如果您有更好的组织方式,请随时对其进行批评).另外,这里还有指向 JSFiddle 的链接,该链接可保存警报.
Seems easy enough. I've built a working model except for it alerts the wrong number. It alerts Button 11 for all the buttons. I know I'm forgetting something simple. Below is my code (feel free to critique it if you have a better way of organizing this). Also here is a link to a JSFiddle that works save for the alert.
var count = 1;
function createBtn(){
var button = document.createElement("button");
button.innerHTML = "Button " + count;
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
alert('Button ' + count);
});
}
function buttonRender(){
for(var i = 0; i < 10; i++){
createBtn();
count++;
}
}
buttonRender();
推荐答案
您应将count传递给该函数.
You should pass count to the function.
function createBtn(count){
var button = document.createElement("button");
button.innerHTML = "Button " + count;
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
alert('Button ' + count);
});
}
function buttonRender(){
for(var i = 0; i < 10; i++){
createBtn(count);
count++;
}
}
https://jsfiddle.net/xw7mhag2/
这篇关于JavaScript按钮返回错误警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!