【问题标题】:on click event not getting the value of textbox in jquery在单击事件中没有获取 jquery 中文本框的值
【发布时间】:2012-12-14 08:45:29
【问题描述】:

在每一行中都有一个文本框和一个按钮,我希望通过各自的文本框单击按钮来获取文本数据。但问题是我为每个按钮单击获得相同的值,因为 textboxID 是相同的......在循环中 我的代码是这样的......有什么方法可以获取每个文本框的值以进行 diff 按钮单击

 <% @obj.each_with_index do |time_sheet, i| %>
   <tr>
     <td style="width:30px;"><input type="text" name="comment"  id='commentId'></td>
     <td class="table-styling"> <button type="button" id="waiver">Waiver</button></td>
   </tr>
  <% end %>


  $('#waiver').live("click", function() {
 var commentVal = $("#commentId").val();
 alert(commentVal); //getting same value for each button click

   });

【问题讨论】:

    标签: jquery ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:
    $(document).on('click', '#waiver', function() {
       var commentVal = $(this).closest('tr').find("#commentId").val();
       console.log(commentVal);
    });
    

    当然,ID 是唯一的,看起来您在循环内大量生产具有相同 ID 的元素,这不是一个好主意,并且会使 javascript 变得很糟糕。

    【讨论】:

      【解决方案2】:

      您正在创建大量具有相同id 属性的元素。 id 属性用于标识 one 元素。没有了。

      改用类:

      <% @obj.each_with_index do |time_sheet, i| %>
          <tr>
              <td style="width: 30px;">
                  <input type="text" name="comment" class="comment" />
              </td>
      
              <td class="table-styling">
                  <button type="button" class="waiver">Waiver</button>
              </td>
          </tr>
      <% end %>
      

      还有你的 JS:

      $(document).on('click', '.waiver', function() {
          var commentVal = $(this).closest('tr').find('.comment').val();
      }); 
      

      【讨论】:

      • 您是如何在按钮内找到输入的?
      • @adeneo: Magic ;) 谢谢,我完全错过了。
      • 那是jQuery版本的巫术吗,如果是,我在哪里可以得到它?
      • @Blender:在 GitHub 上找不到插件页面 :(
      【解决方案3】:

      首先重要的是ID应该是唯一的!

      如果您想获取相应的文本框值,您可以尝试将代码替换为类名而不是 id,如下所示

      <% @obj.each_with_index do |time_sheet, i| %>
       <tr>
       <td style="width:30px;">
         <input type="text" name="comment"  class='comment-textbox'>    </td>
       <td class="table-styling"> 
         <button type="button" class="btn-waiver">Waiver</button></td>
       </tr>
      
       $('.btn-waiver').live("click", function() {
       var commentVal =$(this).closest('tr').find('.comment-textbox').val();
           //or
       var commentVal = $(this).parents('tr:first').find('.comment-textbox').val();
       alert(commentVal); //getting same value for each button click
      
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        • 1970-01-01
        相关资源
        最近更新 更多