如何识别以相同开头但值在 JavaScript 中不同的不同 ID

How to identify different id's that start with the same but vary in a value in JavaScript

你好,我想在 Rails 上用 JavaScript/CoffeeScript 和 Ruby 做点什么: 我有几条评论(每次迭代都在 a 上呈现),当我单击该评论中的按钮时,我想在每条评论下显示一些内容。 我这样做是为了识别按钮和呈现每个评论的代码中的部分:

<div>
    <a id="show-link-<%=comment.id%>" href="#">
        This will show whats in the section
    </a>
</div>
<section id="show-section-<%=comment.id%>">
    This is what I want to show
</section>

然后我想在 coffeescript 中这样做:

$(document).on 'turbolinks:load', ->
  $('#show-link-[SOMEID]').click (event) ->
    event.preventDefault()
    $('#show-section-[SOMEID]').toggle()

而且我希望脚本检测点击了哪个按钮并显示其各自的部分,对于每条评论。 脚本中的 SOMEID 可能会在那里识别一些数字并在函数内部使用它。 希望您能提供帮助,感谢您的宝贵时间!

我无法使用 ruby 或 coffeescript,但只使用 DOM APIthis 怎么样?

// Get all the "buttons"
var links = document.querySelectorAll(".showLink");

// Loop the "buttons" and wire an event handler to the click event
links.forEach(function(element){
  element.addEventListener("click", function(){
    
    // Find the parent of the "button" (the <div>)
    var parent = this.parentNode;
    
    // Go to that div element's next sibling and show it:
    parent.nextElementSibling.setAttribute("class", "show");
  });
});
.section {display:none;}
.show {display:block;}
<div>
    <a id="show-link-<%=comment.id%>" href="#" class="showLink">
        This will show whats in the section
    </a>
</div>
<section id="show-section-<%=comment.id%>" class="section">
    Section 1 Content
</section>

<div>
    <a id="show-link-<%=comment.id%>" href="#" class="showLink">
        This will show whats in the section
    </a>
</div>
<section id="show-section-<%=comment.id%>" class="section">
    Section 2 Content
</section>

<div>
    <a id="show-link-<%=comment.id%>" href="#" class="showLink">
        This will show whats in the section
    </a>
</div>
<section id="show-section-<%=comment.id%>" class="section">
    Section 3 Content
</section>

当你只有一把锤子时...

您为这项工作使用了错误的工具(试图在 id 中嵌入数据)。

使用数据属性和 classes 可以做得更好。使用 class 批量分配点击处理程序并使用数据属性以完整形式存储部分名称,不需要任何处理。

<div>
    <a class='show-link' data-section-id="show-section-<%= comment.id %>" href="#">
        This will show whats in the section
    </a>
</div>
<section id="show-section-<%= comment.id %>">
    This is what I want to show
</section>

然后

$('.show-link').click (event) ->
  event.preventDefault()
  commentSectionId = $(this).data('sectionId')
  $('#' + commentSectionId).toggle()

演示

$('.show-link').click(function(event) {
  var commentSectionId;
  event.preventDefault();
  commentSectionId = $(this).data('sectionId');
  return $("#" + commentSectionId).toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
        <a class='show-link' data-section-id="show-section-1" href="#">
            This will show whats in the section
        </a>
    </div>
    <section id="show-section-1" style='display: none'>
        This is what I want to show
    </section>