jQuery:this.attr() 不是函数? [英] jQuery: this.attr() not a function?

查看:36
本文介绍了jQuery:this.attr() 不是函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定我是否没有在正确的范围内使用它或什么,但我有一个脚本,它基本上捕获链接点击并导致页面在转到链接页面之前淡出.但是,如果链接是 JavaScript onclick,则脚本将失败.

I'm not quite sure if I'm not using this in the correct scope or what, but I have a script that basically captures a link click and causes the page to fade out before going to the linked page. However, if the link is a JavaScript onclick, the script fails.

这是我的代码:

<script type="text/javascript">

    pageObj = {
        init: function(){
            $("body").fadeTo("slow", 1);
        },
        redirectPage: function(redirect){
            window.location = redirect;
        },
        linkLoad: function(location){
            $("body").fadeOut(1000, this.redirectPage(location));
        }
    };

    $(document).ready(function() {
        pageObj.init();

        $("a").click(function(e){
            e.preventDefault();
            if (this.attr('onclick') !== undefined) {
                eval(this.attr('onclick').val());
            } else {
                var location = this.href;
                pageObj.linkLoad(location);
            }
        });
    });

</script>


如您所见,我正在尝试检查链接是否具有 onclick 属性,然后调用 onclick 函数(如果存在).我怎样才能做到这一点?


As you can see, I'm trying to do a check to see if the link has the onclick attribute, and then call the onclick function if it exists. How can I achieve this?

推荐答案

虽然 Diodeus 是正确的,但您需要在使用 attr() 之前将 this 包装在 jQuery 集合中(它是 jQuery 集合的方法,而不是 HTMLElement),您也可以跳过 attr().

While Diodeus is correct that you need to wrap this in a jQuery collection before using attr() (it's a method of a jQuery collection, not of an HTMLElement), you can just as well skip attr().

$("a").click(function(e){
    var location;
    e.preventDefault();
    if ($.isFunction(this.onclick)) {
        this.onclick.call(this, e);
    } else {
        location = this.href;
        pageObj.linkLoad(location);
    }
});

请注意,我使用了属性(当加载 HTML 文档时,属性通常被预加载到属性中,on___ 属性被预加载为方法.另外请注意,我使用了 this.onclick.call() 而不是 eval(),为 onclick 方法设置正确的 this,并确保对事件对象的访问为一个论点.

Note that I used the property (when an HTML document loads, attributes are usually preloaded into properties, with on_______ attributes being preloaded as methods. Also note that I used this.onclick.call() rather than eval(), setting the correct this for onclick methods, and ensuring access to the event object as an argument.

这篇关于jQuery:this.attr() 不是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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