简体   繁体   English

jQuery + Rails:如何获取单击按钮的用户的ID

[英]jQuery + Rails: How to get id of button user clicked

I have spent hours trying to resolve this problem and reviewing other similar StackOverflow questions (1) (2) , but none seem to have an answer to my problem.. 我已经花费了数小时试图解决此问题并查看其他类似的StackOverflow问题(1) (2) ,但是似乎没有一个答案可以解决我的问题。

I can't get past this error: ReferenceError: id is not defined . 我无法摆脱这个错误: ReferenceError: id is not defined Alert does not show too. 警报也不显示。

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

I have tried the following ways to using the id variable but none work. 我尝试了以下使用id变量的方法,但没有任何效果。

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

However, when i remove the chunk of code below the alert, the alert pops up with the correct id belonging to the button. 但是, 当我删除警报下方的代码块时,会弹出警报,并带有属于该按钮的正确ID。

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

View partial: Button id references a ruby local variable id="<%= name %>" 查看部分视图:按钮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 %>

As you've noted, the error is chaining functions in the click listener. 正如您已经指出的,错误是单击侦听器中的链接功能。

In order to get the id attribute, you can use the jQuery attr function, like: 为了获得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> 

Here, in your code I will beautify it to see your mistake: 在这里,我将在您的代码中美化它以查看您的错误:

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

notice the second function has 注意第二个功能有

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

but the id is not defined yet 但编号尚未定义

try 尝试

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

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

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