问题
Following is an excerpt from my view
<ul id="ScreenNav">
<li id="1" class="Active"> One </li>
<li id="2"> Two </li>
<li id="3"> Three </li>
</ul>
I have some scripts which perform an ajax call based on the list element selected.
$('#ScreenNav').on('click', 'li', function () {
$(this).siblings().removeClass('active');
$(this).addClass('active');
var index = $(this).attr('id');
//ajax call to a controller action
});
Somehow the ajax call to the controller action is happening while the statements prior to that don't have any effect. While debugging I found the statement $('this').attr('id')
to be throwing an error saying 'Object doesn't support property or method 'attr''.
I tried fiddling but face the same issue. http://jsfiddle.net/29KR9/1/. Is $('this')
not being identified correctly? In that case how is the ajax call proceeding as expected? What is wrong with the code?
EDIT: My apologies! The fiddle is working as expected. As @Anton has pointed out, I didn't include jQuery. However I still don't get why my the adding and removing of class doesn't work. The difference between the fiddle and my code is that in my code the scripts are bound to the list elements which are dynamic html.
回答1:
please use this code in $(document).ready(); like this
$(document).ready(function () {
$('#ScreenNav').on('click', 'li', function () {
$(this).siblings().removeClass('active');
$(this).addClass('active');
});
});
来源:https://stackoverflow.com/questions/21529618/object-doesnt-support-property-or-method-attr