jQuery Duplicates of Appended Elements On Click -
i attempting append content element depending on link clicked. if content exists, should not post duplicate of content. problem having duplicates being posted every link besides first 1 clicked.
the links content , ids generated from:
<a href='#' id="a">a</a> <a href='#' id="b">b</a> <a href='#' id="c">c</a>
this jquery script supposed check if id of link clicked matches id of li element in list. if not, appends new li element same id link clicked.
<ul id="list"></ul> <script> $(document).on('click', 'a', function(){ if($('#list').children('li').attr('id') != $(this).attr('id')) { var content = '<li id=' + $(this).attr('id') + '>' + $(this).html() + '</li>'; $('#list').append(content) } }) </script>
the ids , content being generated fine script works on first element clicked, output like:
a b b c c
try debugging:
example
you see .children().attr()
returns first element.
to tackle issue, can go on each subelement , see if equals clicked id
:
$('a').click(function(){ var clickedid = $(this).attr('id'); var add = true; $('li','#list').each(function(){ if ($(this).attr('id') == clickedid) { add = false; } }); if (add) { var content = '<li id=' + $(this).attr('id') + '>' + $(this).html() + '</li>'; $('#list').append(content) } })
if equals 1 of list items, not added.
for future problems: try approaching problem simple logic first.
and javascript's alert( )
method friend: great little tool debugging.
the corresponding jsfiddle can found here:
Comments
Post a Comment