javascript - How can I get id of span and make it display none which is dynamically generated? -
i have created span tags dynamically , appended div. want id, 1 select , delete it. jquery tagit. below using not working. see id can when click particular span.
$('span').on('click', function (e){ alert(e.target.id); });
you don't need id (and span may not have one), have reference element: this. that's standard jquery behavior. (in fact, it's standard across various ways can hook events without jquery too.)
so
$('span').on('click', function() { $(this).remove(); // removes 1 clicked }); (or, yes, add e , use e.target: $(e.target).remove();)
re comment:
i tried using code giving alert click event not firing.
that suggests spans in question don't exist of when code runs, , don't end hooking click event.
to deal that, want delegated handler: in dev tools, right-click 1 of these spans , find common ancestor have does exist of when code runs. (in worst case, document, it's better scope things more tightly.) then:
$('selector-for-that-ancestor-element').on('click', 'span', function() { $(this).remove(); // removes 1 clicked }); see on details. also, if spans have identifying characteristics (like class or attribute), might want include in delegation selector above more specific.
Comments
Post a Comment