admin管理员组文章数量:1351851
I'm trying to add a class to a parent <li>
, this is what I have been trying with no result:
function calendaractive(){
$(this).parent('li').addClass("active");
}
HTML
<li>
<a href="javascript:void(0)" onclick="calendaractive();">2009</a>
</li>
Why does this not work?
I'm trying to add a class to a parent <li>
, this is what I have been trying with no result:
function calendaractive(){
$(this).parent('li').addClass("active");
}
HTML
<li>
<a href="javascript:void(0)" onclick="calendaractive();">2009</a>
</li>
Why does this not work?
Share Improve this question edited Feb 18, 2013 at 16:29 Tom 16.2k4 gold badges39 silver badges48 bronze badges asked Feb 6, 2013 at 10:15 user1617218user1617218 1-
You need not have that
'li'
insideparent()
– KBN Commented Feb 6, 2013 at 10:17
4 Answers
Reset to default 7Try.
Pass this
at your function binding
<li>
<a href="javascript:void(0)" onclick="calendaractive(this);">2009</a>
</li>
change the JS accordingly
function calendaractive(anchorLink){
$(anchorLink).parent().addClass("active");
}
It's better to not mix your HTML and JavaScript. It would be better to check for the click within the JavaScript itself:-
$(document).ready(function(){
$('li > a').on('click', function(e) {
$(this).parent().addClass('active');
});
});
Keeping JavaScript separate from the HTML will make it easier to maintain (the same argument goes with CSS).
You should add the event using JQuery instead of onClick method:
JS Should be something like this instead:
$(document).ready(function(){
$("a").click(function() {
$(this).parent('li').addClass("active");
});
});
HTML Like this
<li>
<a href="#">2009</a>
</li>
Note this will add to all anchor links, use a class if you want to only add the click event to certain anchor links
the this
keyword in javascript means different things in different places. Sometimes it is the window, sometimes it is the function where it is used, sometimes something different. It depends on the method of invocation of the function. There is more info (and more accurate) here: How does the "this" keyword work?
So when you wrote $(this)
jQuery thought you mean this class should be added to the this object whichever it is.
If you put a selector by id as an argument to jQuery, or better yet pass an argument, your code should work.
本文标签: javascriptAddClass to parent ltligt on functionStack Overflow
版权声明:本文标题:javascript - AddClass to parent <li> on function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743664052a2518430.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论