Handlebars & Jquery: Dynamically generated ids

五迷三道 提交于 2020-01-17 05:49:25

问题


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

The original handlebars code is this:

{{#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}}

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.

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.

Appreciate the help!


回答1:


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
});



回答2:


You can not have identical id on different element. That's why your code isn't working. Give each element a different id. You may use {{@index}} to get the current iteration count and then use it in the id to generate a dynamic id i.e:

<input class="form-control" type="text" id="comment_{{@index}}" value={{comment}}>

You should do the same for the button as well. In your jQuery code, you can then access the input using prev() method

You can then access it using jquery. Or you may also use class instead of id. That would be better.




回答3:


What you are doing is actually wrong. As you know already, IDs should not be duplicated. You should be using something like this:

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

And the next one is in the jQuery:

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


来源:https://stackoverflow.com/questions/32166258/handlebars-jquery-dynamically-generated-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!