【问题标题】:How do I get an element with a specific ID from getElementsByClassName?如何从 getElementsByClassName 获取具有特定 ID 的元素?
【发布时间】:2020-05-29 06:29:23
【问题描述】:

编辑:已解决。谢谢大家!

我是编程新手 :D 我的代码如下。这是交易:我有多个按钮,但我想让它在任何时候点击这些按钮中的任何一个时都会发生同样的事情,但每个按钮也有一个特定的值,我也希望这个特定的值是打印出来。我的代码遍历文档并查看具有“editButton”类的所有元素,并正确识别所有按钮,但问题是无论我按下哪个按钮,我总是得到最后一个按钮的值,因为 var id仅在 for 循环完成后分配,并且位于最后一个元素上。我尝试创建一个全局变量并为其赋值,但结果是一样的。在转到 .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>

【问题讨论】:

  • 我将您的代码移入了代码 sn-p。您能否添加必要的 HTML 来重现您的问题?
  • 我的按钮是自动生成的,每个按钮都与数据库中的一个元素相关联。我添加了按钮的代码,但我认为其他任何内容都不是真正相关的。
  • 您可以复制并粘贴生成的代码(客户端),以便我们更好地了解您的问题。

标签: javascript for-loop dom


【解决方案1】:

实际上,最好的方法之一是click() 事件上使用editButton 类监听每个按钮,而不是做一个巨大的for 循环来添加onclick 事件使用$(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>

【讨论】:

    【解决方案2】:

    在运行 onclick 函数时用 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/

    【讨论】:

      【解决方案3】:

      您需要查看 JavaScript closures 以及它们如何解决此问题。 当您在 for 循环中添加事件侦听器时,您需要在 JS 中小心。当您单击按钮时,for 循环已经执行,每次按下按钮时您将只有最后一个 i 值。您可以使用IIFE 模式,let 关键字来解决这个问题。

      下面列出了解决此问题的一种简单方法。

      <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]); 
      
              }
          }
      }); 
      

      您可以在JavaScript closure inside loops – simple practical example阅读更多相关信息

      【讨论】:

        【解决方案4】:

        在你的代码中..

         var id = anchor.value;
        

        可能是

         var id = anchor.id;
        

        但我建议你使用事件委托

        如果你有这样的html

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

        你可以像下面这样编码。

        $(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); 
            });
        }
        

        【讨论】:

          【解决方案5】:

          您可以使用getAttribute。喜欢:

          var anchors = document.getElementsByClassName('editButton');
          
          // Id of anchors
          id_of_anchor = anchors.getAttribute("id");
          

          Refs

          编辑

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

          【讨论】:

          • 那只会给我一个 id 的列表。如何识别我点击的特定按钮?
          【解决方案6】:

          您的应用程序中有 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);
                      });
                  });
              });
          });
          

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

          【讨论】:

          • 试过了,不行,抱歉。另外,我注意到你在 .each 函数中有两个参数 a 和 b,但是 a 没有在任何地方使用,那么为什么需要它?
          • 只要检查一下你会发现它正在工作的小提琴,它在你的情况下不起作用可能你没有 $(b).val() 如果你想得到你应该写的文本 $( b).text(), a => index, b=> item 我用过 b, 我不需要 a.
          • @SabaKvesitadze 我为你修好了,现在点击事件会给你项目的 id。
          猜你喜欢
          • 1970-01-01
          • 2022-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-16
          • 1970-01-01
          • 1970-01-01
          • 2011-10-17
          相关资源
          最近更新 更多