javascript 如何拥有多个具有相同 id 值的按钮,并且当单击任何按钮时应该弹出窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51287162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:29:43  来源:igfitidea点击:

How to have multiple buttons of same id value and when click on any button the pop-up should come?

javascripthtml

提问by Prajna Hegde

I have multiple buttons having same element id, But when I click on first button, the pop-up is coming. If I click on any other buttons pop-up will not come. How can I make it possible.

我有多个具有相同元素 ID 的按钮,但是当我单击第一个按钮时,弹出窗口即将到来。如果我单击任何其他按钮,则不会弹出。我怎样才能使它成为可能。

<form method="post" action="trial.php">

<!-- Trigger/Open The Modal -->
<input type="button" id="myBtn" value="assign"></input>
<input type="button" id="myBtn" value="asd"></input>
<input type="button" id="myBtn" value="assign"></input>
<input type="button" id="myBtn" value="assign"></input>
<input type="button" id="myBtn" value="assign"></input>

<!-- The Modal -->
<div id="myModal" class="modal">
    <!-- Modal content -->
    <div class="modal-content">
        <span class="close">&times;</span>
        <p>Assign Project</p>
        <hr style="height:0.25px; background:black;"></hr>
        <div class="container">
          <div class="row">
              <p class="col-md-10"><br/>Assign Project to a Existing Team : 
              <a class="btn btn-primary" id="ExistingTeam" value="Existing Team" href="google.com">Existing Team</a></p>
          </div>
          <div class="row">
              <p class="col-md-10"><br/>Create a new Team and Assign Project : 
              <a class="btn btn-primary" id="CreateTeam" value="Create Team" href="google.com">Create Team</a></p>  
          </div>
        </div>
    </div>
</div>
</form>

These is the javascript I am using for pop-up

这些是我用于弹出窗口的 javascript

<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

回答by Ullas Hunka

When you assign the same ID to more than one element this scenario happens. Actually when you try to call the element using id code only calls the first element.

当您将相同的 ID 分配给多个元素时,就会发生这种情况。实际上,当您尝试使用 id 代码调用元素时,只会调用第一个元素。

So to remove this error there are multiple solutions:

因此,要消除此错误,有多种解决方案:

  1. Use the class name and assign the event through the loop
  2. Use different IDs
  3. Access the elements using the tag and check whether its id is the id assigned by you.
  1. 使用类名并通过循环分配事件
  2. 使用不同的 ID
  3. 使用标签访问元素并检查其 id 是否是您分配的 id。

This pagehas mentioned everything which you require to get over your problem.

页面已提及解决问题所需的所有内容。

回答by Christos

You should have unique ids for your HTML elements. In order you achieve that you want the common practice is to use a pseudo css class prefixed with js, in order for this to be evident to the readers of your code that this class is used in js script.

你的 HTML 元素应该有唯一的 id。为了实现你想要的,通常的做法是使用一个以 js 为前缀的伪 css 类,以便让你的代码的读者清楚地知道这个类在 js 脚本中使用。

var buttons = document.getElementsByClassName('jsBtn');
for(var i=0; i<buttons.length; i++){
    buttons[i].addEventListener("click", function(){ console.log("Hello"); })
}
<input type="button" id="btn1" class="jsBtn" value="button1"/>
<input type="button" id="btn2" class="jsBtn" value="button2"/>

A better approach it would be to place all the buttons in a div and assign the pseudo css class to this div.

更好的方法是将所有按钮放在一个 div 中,并将伪 css 类分配给这个 div。

var btnContainer = document.getElementsByClassName("jsBtnContainer");
btnContainer[0].addEventListener("click", function() { console.log("Hello"); });
<div class="jsBtnContainer">
    <input type="button" id="btn1" class="jsBtn" value="button1"/>
    <input type="button" id="btn2" class="jsBtn" value="button2"/>
</div>

Doing so, you would have only one event listener instead of nlisteners, where nis the number of buttons in your document. Fewer listeners means better performance on the loading of the page, since fewer listeners would have to be registered.

这样做,您将只有一个事件侦听器而不是n侦听器,其中n是文档中按钮的数量。更少的监听器意味着更好的页面加载性能,因为需要注册的监听器更少。

The above technique is called DOM Event Delegation.

上述技术称为DOM 事件委托

回答by Sourajit Karada

It is not recommended to use same id for multiple elements. Replace id with class attribute. I have done a sample code that will give you a brief idea on coding part. Kindly check.

不建议对多个元素使用相同的 id。用 class 属性替换 id。我已经完成了一个示例代码,可以让您对编码部分有一个简要的了解。好心检查。

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Learn Javascript</title>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    </head>
    <body>
        <form action="">
            <input type="button" value="button 1" class="myBtn">
            <input type="button" value="button 2" class="myBtn">
        </form>
    </body>
    </html>
   jQuery(document).ready(function(){
      jQuery('.myBtn').on('click', function(){
            alert('You have clicked');
      });
});

*

*