jQuery: this.attr() not a function?

前端 未结 2 1596
眼角桃花
眼角桃花 2020-12-01 23:09

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 goin

相关标签:
2条回答
  • 2020-12-02 00:01

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

    This forces it into the context of jQuery.

    0 讨论(0)
  • 2020-12-02 00:12

    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.

    0 讨论(0)
提交回复
热议问题