简体   繁体   English

如何从 getElementsByClassName 获取具有特定 ID 的元素?

[英]How do I get an element with a specific ID from getElementsByClassName?

EDIT: SOLVED.编辑:已解决。 Thanks everyone!感谢大家!

I'm new to programming:D My code is below.我是编程新手:D 我的代码如下。 Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out.这是交易:我有多个按钮,但我想让它在任何时候点击这些按钮中的任何一个时都会发生同样的事情,但每个按钮也有一个特定的值,我也希望这个特定的值是打印出来。 My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element.我的代码遍历文档并查看所有带有“editButton”class 的元素,并正确识别所有按钮,但问题是无论我按下哪个按钮,我总是得到最后一个按钮的值,因为 var id仅在 for 循环完成后分配,并且位于最后一个元素上。 I tried creating a global variable and assigning the value to it, but the result is the same.我尝试创建一个全局变量并为其赋值,但结果是一样的。 I tried ending the for loop before moving on to.done (function (data), but I got an error. Can someone help me out? Thanks!在继续 to.done (function (data) 之前,我尝试结束 for 循环,但出现错误。有人可以帮我吗?谢谢!

 $(document).ready(function() { var anchors = document.getElementsByClassName('editButton'); for (var i = 0; i < anchors.length; i++) { var anchor = anchors[i]; anchor.onclick = function() { $.ajax({ method: "GET", url: "/testedit.php", }).done(function(data) { var id = anchor.value; /* from result create a string of data and append to the div */ var result = data; var string = '<p>ID is ' + id + '</p><br>'; $("#records").html(string); }); } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="records"></div>

Actually, instead of doing a huge for loop to add onclick events to your buttons, one of the best ways to do this is to listen to each button with editButton class on click() event then use$(this) which refers to the exact clicked button .实际上,与其做一个巨大的 for 循环来将onclick事件添加到您的按钮,最好的方法之一是click()事件上使用editButton class 监听每个按钮,然后使用$(this) ,它指的是确切的点击按钮 After that, you can use each individual button to do whatever you want.之后,您可以使用每个单独的按钮来做任何您想做的事情。

So your final code should be something like this:所以你的最终代码应该是这样的:

 $(document).ready(function() { $('.editButton').click(function() { console.log('innerHTML is:', $(this).html()) console.log('id is:', $(this).attr('id')) $.ajax({ method: "GET", url: "/testedit.php", }).done(function(data) { var id = $(this).value; /* from result create a string of data and append to the div */ var result = data; var string = '<p>ID is ' + id + '</p><br>'; $("#records").html(string); }); }) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="records"> <button class="editButton" id="firstButton">button 1</button> <button class="editButton" id="secondButton">button 2</button> <button class="editButton" id="thirdButton">button 3</button> <button class="editButton" id="fourthButton">button 4</button> </div>

You can use getAttribute .您可以使用getAttribute Like:喜欢:

var anchors = document.getElementsByClassName('editButton');

// Id of anchors
id_of_anchor = anchors.getAttribute("id");

Refs 参考文献

EDIT编辑

anchor.onclick = function() {
    id_of_anchor = $(this).attr("id");
});

You have jQuery in your application, there is easier and more readable way to do it with jQuery;您的应用程序中有 jQuery,使用 jQuery 可以更简单、更易读的方法;

$(document).ready(function() {
    $(".editButton").each(function(a, b) {
        $('#' + $(b).attr('id')).on('click', function() {
            $.ajax({
                method: "GET",
                url: "/testedit.php",
            }).done(function(data) {
                var id = $(b).attr('id');

                /* from result create a string of data and append to the div */

                var result = data;
                var string = '<p>ID is ' + id + '</p><br>';

                $("#records").html(string);
            });
        });
    });
});

Example: https://jsfiddle.net/wao5kbLn/示例: https://jsfiddle.net/wao5kbLn/

You need to look in to JavaScript closures and how they work to solve this.您需要查看 JavaScript closures以及它们如何解决此问题。 When you add event listeners inside a for loop you need to be careful in JS.当您在 for 循环中添加事件侦听器时,您需要在 JS 中小心。 When you click the button, for loop is already executed and you will have only the last i value on every button press.当您单击按钮时,for 循环已经执行,每次按下按钮时您将只有最后一个i值。 You can use IIFE pattern, let keyword to solve this.你可以使用IIFE模式, let关键字来解决这个问题。

One simple way to resolve this issue is listed below.下面列出了解决此问题的一种简单方法。

<div id="records"></div>

<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>


<script type="text/javascript"> 
  $(document).ready(function(){ 
    var anchors = document.getElementsByClassName('editButton');
    for(var i = 0; i < anchors.length; i++) {           

            //Wrap the function with an IIFE and send i value to the event listener

            (function(anchor){

             anchor.onclick = function() {
               $.ajax({ 
                  method: "GET", 
                  url: "/testedit.php",
               }).done(function( data ) { 
                  var id = anchor.value;

                  /* from result create a string of data and append to the div */

                  var result= data; 
                  var string='<p>ID is '+id+'</p><br>';

                  $("#records").html(string); 
              });
            }

           })(anchors[i]); 

        }
    }
}); 

You can read more about this in JavaScript closure inside loops – simple practical example您可以在JavaScript 循环内闭包中阅读更多相关信息 - 简单的实际示例

save the button with button = this when run the onclick function and use it当运行 onclick function 并使用它时,用 button = this 保存按钮

 $(document).ready(function(){ 
 var anchors = document.getElementsByClassName('editButton');
   for(var i = 0; i < anchors.length; i++) {
     var button;
     var anchor = anchors[i];
     anchor.onclick = function() {
       button = this;
       $.ajax({ 
         method: "GET", 
         url: "/testedit.php",
       }).done(function( data ) {                   


         /* from result create a string of data and append to the div */

         var result= data; 
         var string='<p>ID is '+ button.value +'</p><br>';

         $("#records").html(string); 
       }); 
     }
   }
}); 

https://jsfiddle.net/x02srmg6/ https://jsfiddle.net/x02srmg6/

In your code..在你的代码中..

 var id = anchor.value;

could be可能

 var id = anchor.id;

but I recommend you to use event delegation但我建议您使用事件委托

If you have a html like this如果您有这样的 html

<div id="buttonArea">
  <a class="editButton" id="1"/>
  <a class="editButton" id="2"/>
  <a class="editButton" id="3"/>
  .......(so many buttons)
</div>

you can code like below.你可以像下面这样编码。

$(document).ready(function(){ 
  $('#buttonArea').on('click', 'a.editButton', function (event) {
    var anchor = event.currentTarget;
    $.ajax({ 
      method: "GET", 
      url: "/testedit.php",
    })
    .done(function(data) { 
      var id = anchor.id;

      /* from result create a string of data and append to the div */

      var result= data; 
      var string='<p>ID is '+id+'</p><br>';

      $("#records").html(string); 
    });
}

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

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