车把jQuery:动态生成的ID [英] Handlebars & Jquery: Dynamically generated ids

查看:47
本文介绍了车把jQuery:动态生成的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 handlebars 页面上生成一个动态的 form button .

I am generating a dynamic form and button on a handlebars page.

原始的车把代码是这样的:

{{#each record}}
    <input class="form-control" type="text" id="comment" value={{comment}}> 
    <button class="btn small btn-success" id="btn-savecomment">SAVE COMMENT</button>
{{/each}}

并且我有一个jquery脚本可以在按下每个按钮时保存表单的内容:

and I have a jquery script to save the contents of the form when each button is pressed:

$(document).ready (
    function() {
        $(document).on('click','#savecomment',function(event){
            // save id: comment to record
    );

目的是允许用户键入评论,然后将其保存到每个记录中.

The purpose is to allow the user to type in a comment and then save it to each record.

但是,如何在查看注释时确保按钮标识正确的输入表单?当我单击一个特定的按钮时,因为它们都具有相同的ID,所以它仅从第一条记录中检索评论.

However how can I ensure the button identifies the right input form when looking the comment? When I click on a particular button it only retrieves the comment from the first record because all of them have identical ids.

感谢帮助!

推荐答案

好吧,您可以动态生成ID,但是很可能您应该只使用更合适的类或数据值(或类似值):

Well, you could dynamically generate the IDs, but most likely you should just should just be using classes or data-values (or similar) that are a better fit:

{{#each record}}
    <input class="form-control" type="text" data-comment={{@index}} value={{comment}}> 
    <button class="btn small btn-success" data-trigger="save">SAVE COMMENT</button>
{{/each}} 

$(document).on("click", "[data-trigger='save']", function (evt) {
  var commentID = $(this).prev().data("comment"); //index number, can be pretty much anything
});

这篇关于车把jQuery:动态生成的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆