jQuery: this.attr() not a function?

2019-01-09 17:15发布

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.

Here's my code:

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


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?

2条回答
Explosion°爆炸
2楼-- · 2019-01-09 17:52

Use: $(this).attr instead of this.attr

This forces it into the context of jQuery.

查看更多
淡お忘
3楼-- · 2019-01-09 17:56

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

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.

查看更多
登录 后发表回答