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

cha*_*tor 25 jquery attributes object

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

这是我的代码:

<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>
Run Code Online (Sandbox Code Playgroud)


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

Dio*_*ane 85

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

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

  • 我本以为这也会起作用,但是,我使用它得到 `$(this).attr("onclick").val is not a function`。 (2认同)
  • 在这种情况下,您不需要 .val() 。 (2认同)

eye*_*ess 6

虽然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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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