简体   繁体   English

在for循环(JS)中捕获this.id

[英]Catch this.id inside for loop (JS)

HTML 的HTML

<button class="button" id="1">Button 1</button>
<button class="button" id="2">Button 2</button>

JS JS

const button = document.getElementsByClassName('button');

function chooseButton() {
    // works
    let buttonId = this.id;
    console.log('You choose button' + buttonId);
};

// Check for button click
for (var i = 0; i < button.length; i++) {
    button[i].addEventListener('click', chooseButton, false);
}

How do i listen for buttonId, catch it and use it outside the function? 我该如何收听buttonId,捕获它并在函数之外使用它?

if (buttonId == 1) {
   // do this
}

You should not use let inside function, if you want to access it outside. 如果要在外部访问它,则不应使用let inside函数。 Should be 应该

let  buttonId;
function chooseButton() {
    // works
    buttonId = this.id;
    console.log('You choose button' + buttonId);
};

You need to define the buttonId variable outside the function: 您需要在函数外部定义buttonId变量:

 const button = document.getElementsByClassName('button'); let buttonId; function chooseButton() { buttonId = this.id console.log('You choose button' + buttonId); checkerFunction(); }; for (var i = 0; i < button.length; i++) { button[i].addEventListener('click', chooseButton, false); } function checkerFunction() { if (buttonId == 1) { console.log('TEST :: You choose button' + buttonId); } else { console.log('TEST :: You choose the other button' + buttonId); } } 
 <button class="button" id="1">Button 1</button> <button class="button" id="2">Button 2</button> 

To verify that the value is readable we call the checkerFunction just for testing purposes. 为了验证该值可读,我们仅出于测试目的调用checkerFunction。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM