javascript - Can not add class dynamically in a tag using Jquery -
i need help.i not add class dynamically using jquery. explaining code below.
$.each(obj.cid, function() { $("#ulcategory").append("<li><a href='javascript:void(0)' onclick='savesubcat("+this.id+","+this+")'>" + this.name +</li>"); }); function savesubcat(id,$this){ $($this).addclass("active"); $($this).siblings().removeclass('active'); }
here need add active class on clicked anchor tag in way not happening this.please me.
your first issue you're not wrapping string value in quotes in function call. second problem that, context, this
object. concatenating object string isn't going work expect.
to fix far better use unobtrusive delegated event handler. way this
reference within handler function anyway, don't need pass it. need put id
object in data
attribute can read within event handler.
also note this
refer a
element has no siblings. add class other a
elements need traverse dom parent ul
, find()
them. try this:
try this:
var obj = { cid: [{ id: 'abc', name: 'foo' }, { id: 'xyz', name: 'bar' }] }; var li = $.map(obj.cid, function(o) { return '<li><a href="#" data-id="' + o.id + '">' + o.name + '</a></li>'; }); $('#ulcategory').append(li.join('')).on('click', 'a', function(e) { e.preventdefault(); var $a = $(this); console.log($a.data('id')); $a.addclass('active').closest('ul').find('a').not($a).removeclass('active'); })
.active { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="ulcategory"></ul>
Comments
Post a Comment