简体   繁体   English

当有多个元素时,单击另一个元素时更改元素的属性

[英]Change attribute of element when another element is clicked, when there are multiple elements

I'm trying to disable a textbox when a submit button is clicked - however there are multiple textboxes with submit buttons.我试图在单击提交按钮时禁用文本框 - 但是有多个带有提交按钮的文本框。 The order of the textbox is the same as the order of the button (for example, the 1st button must disable the 1st button).文本框的顺序与按钮的顺序相同(例如,第一个按钮必须禁用第一个按钮)。

As such, I've been using the following code:因此,我一直在使用以下代码:

 window.onload = function() {
    document.querySelectorAll('button')[i].onclick = function fun(i) {
        document.querySelectorAll('input')[i].disabled = true
    }
}

Where i would be the order of the button/textbox. i将在哪里是按钮/文本框的顺序。

Thanks in advance for your help.在此先感谢您的帮助。

Try using closest which should work in this case.尝试使用 closest ,在这种情况下应该可以使用。 Also I am not sure about how you iterate through the querySelectAll, but I may just not be aware of the shorthand.此外,我不确定您如何遍历 querySelectAll,但我可能只是不知道速记。 Change to:改成:

window.onload = function() {
    const allButtons = document.querySelectorAll('button');
    allButtons.forEach(function(button) {
      button.addEventListener('click', function(e) {
          e.target.closest('input').disabled = true;
      });
});  

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

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