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

查看:90
本文介绍了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(),设置了正确的this用于onclick方法,并确保对事件对象的访问作为参数.

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天全站免登陆