javascript - What is this issue, and how to prevent by jQuery's own way? -
i implementing append operation using $.each
- method. result funny(getting double time of elements!). may have workaround fix this.
but want understand real issue here, there way fix using jquery
's own way?
thanks in advance.
var data = ["orange", "apple"]; var temp = function() { var template = '<dl class="dropdown"><dt> <div class ="dropdownclass" ><span class="hida">select</span> <span class="multisel"></span> </div></dt><dd><div class="mutliselect"><ul><li><input type="checkbox" value="control" />control node</li><li><input type="checkbox" value="border" />border node</li</ul></div></dd></dl>'; return $(template).clone(); } $(document).ready(function() { var tr; var ut $.each(data, function(i, value) { tr = $('<tr />', { id: + 'id' }); ut = temp(); ut.addclass('hema' + i).click(function() { alert($(this).prop('class')); }); tr.append(ut); tr.appendto('tbody'); //getting multple instance!!! }) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <th>title</th> </tr> <tbody> </tbody> </table>
the issue because html invalid. tbody
must encompass all tr
elements. because had tr
outside of tbody
html renderer added second tbody
around - can see if check original snippet in dom inspector. hence when appended tbody
content duplicated across both elements.
if fix html, problem goes away:
var data = ["orange", "apple"]; var temp = function() { var template = '<dl class="dropdown"><dt><div class ="dropdownclass" ><span class="hida">select</span> <span class="multisel"></span> </div></dt><dd><div class="mutliselect"><ul><li><input type="checkbox" value="control" />control node</li><li><input type="checkbox" value="border" />border node</li</ul></div></dd></dl>'; return $(template); } $(document).ready(function() { $.each(data, function(i, value) { var $tr = $('<tr />', { id: + 'id' }); var $ut = temp().addclass('hema' + i); $tr.append($ut).appendto('tbody'); }) $('tbody').on('click', '.dropdown', function() { alert($(this).prop('class')); }); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody> <!-- note tbody here --> <tr> <th>title</th> </tr> </tbody> </table>
note made couple of amendments js logic too; there's no need clone()
you're creating new element anyway, made var declarations local each
loop , used single delegated event handler instead of attaching 1 every element in loop.
Comments
Post a Comment