【问题标题】:jQuery + Rails: How to get id of button user clickedjQuery + Rails:如何获取单击的按钮用户的 ID
【发布时间】:2017-10-16 07:34:57
【问题描述】:

我花了几个小时试图解决这个问题并查看其他类似的 StackOverflow 问题(1)(2),但似乎没有人能回答我的问题..

我无法克服这个错误:ReferenceError: id is not defined。警报也不显示。

  $("button.btn-tag-cat").click(function(e){
    e.preventDefault();
    var id = $(this).prop('id');
    alert(id);
    id.find('span').show();
    }, function(){
    id.find('span').hide();
  });

我已经尝试了以下方法来使用 id 变量,但都不起作用。

$(id).find('span').show();
$("#" + id).find('span').show();

但是,当我删除警报下方的代码块时,会弹出警报,其中包含属于按钮的正确 ID。

  $("button.btn-tag-cat").click(function(e){
    e.preventDefault();
    var id = $(this).prop('id');
    alert(id);
  });

查看部分: 按钮 id 引用了一个 ruby​​ 局部变量 id="<%= name %>"

  <% q.categories_name_in.each do |name|  %>
    <button type="button" class="btn btn-outline-primary btn-lg btn-tag-cat" id="<%= name %>"><%= name %><span class='glyphicon glyphicon-remove'></span></button>
  <% end %>

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby


    【解决方案1】:

    正如您所指出的,错误在于点击侦听器中的链接函数。

    为了获取id属性,可以使用jQuery的attr函数,比如:

    $("button.btn-tag-cat").click(function(e) {
      e.preventDefault();
      var id = $(this).attr('id');
      alert(id);
      $('#' + id).find('span').show();
    });
    

    $("button.btn-tag-cat").click(function(e) {
      e.preventDefault();
      var id = $(this).attr('id');
      alert(id);
      $('#' + id).find('span').show();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <button class="btn-tag-cat" id="hallo">Press</button>

    【讨论】:

      【解决方案2】:

      在这里,我会在你的代码中美化它以查看你的错误:

      $("button.btn-tag-cat").click(
        function(e) {
          e.preventDefault();
          var id = $(this).prop('id');
          alert(id);
          id.find('span').show();
        },
      
        function() {
          id.find('span').hide();
        }
      );
      

      注意第二个函数有

        function() {
          id.find('span').hide(); // right here
        }
      

      但是id还没有定义

      试试

        function() {
          var id = $(this).prop('id'); // this first
          id.find('span').hide();
        }
      

      【讨论】:

      • 感谢您的明确回复,但是,我现在收到此错误:TypeError: id.find is not a function
      • 使用$(id) 代替id。
      • ID 是一个字符串。使用$('#' + id).find(...)
      猜你喜欢
      • 2011-07-22
      • 2021-09-07
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2018-01-25
      • 2011-01-06
      相关资源
      最近更新 更多