问题
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, ID
s 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