您好,我正在尝试使用 JavaScript/CoffeeScript 和 Ruby on Rails 做一些事情: 我有几个评论(每次迭代都会呈现),当我单击该评论中的按钮时,我想在每个评论下显示一些内容。 我这样做是为了识别按钮和呈现每个评论的代码中的部分:
<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 可以识别其中的某个数字并在函数内使用它。 希望您能提供帮助,感谢您的宝贵时间!
最佳答案
当你只有一把锤子时......
您使用了错误的工具来完成这项工作(试图将数据嵌入到 ID 中)。
使用数据属性和类可以更好地完成此操作。使用类批量分配点击处理程序,并使用数据属性以完整形式存储部分名称,这不需要任何处理。
<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>
关于javascript - 如何在 JavaScript 中识别以相同开头但值不同的不同 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40981920/