对象不支持属性或方法"attr" [英] Object doesn't support property or method 'attr'

查看:114
本文介绍了对象不支持属性或方法"attr"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的摘录

<ul id="ScreenNav">
    <li id="1" class="Active"> One </li>
    <li id="2"> Two </li>
    <li id="3"> Three </li> 
</ul> 

我有一些脚本可以根据所选的列表元素执行ajax调用.

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
});

以某种方式发生对控制器动作的ajax调用,而在此之前的语句没有任何效果.调试时,我发现语句 $('this').attr('id')抛出错误,提示对象不支持属性或方法" attr".

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''.

我尝试摆弄,但面临同样的问题. http://jsfiddle.net/29KR9/1/.是否无法正确识别 $('this')?在这种情况下,ajax调用将如何按预期进行?代码有什么问题?

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?

我很抱歉!小提琴正在按预期工作.正如@Anton指出的那样,我没有包括jQuery.但是我仍然不明白为什么我的班级添加和删除不起作用.小提琴和我的代码之间的区别在于,在我的代码中,脚本绑定到了动态html的列表元素.

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.

推荐答案

请在$(document).ready();中使用此代码.像这样

please use this code in $(document).ready(); like this

$(document).ready(function () {
        $('#ScreenNav').on('click', 'li', function () {           
            $(this).siblings().removeClass('active');
            $(this).addClass('active');

        });
});

这篇关于对象不支持属性或方法"attr"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆