jQuery:this.attr() 不是函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9164652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:26:37  来源:igfitidea点击:

jQuery: this.attr() not a function?

jqueryobjectattributes

提问by chaoskreator

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.

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

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 onclickattribute, and then call the onclickfunction if it exists. How can I achieve this?


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

采纳答案by eyelidlessness

While Diodeus is correct that you need to wrap thisin 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().

虽然 Diodeus 是正确的,您需要this在使用之前包装在 jQuery 集合中attr()(它是 jQuery 集合的方法,而不是HTMLElement),但您也可以跳过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 thisfor onclickmethods, and ensuring access to the event object as an argument.

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

回答by Diodeus - James MacFarlane

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

用途:$(this).attr代替this.attr

This forces it into the context of jQuery.

这迫使它进入 jQuery 的上下文。