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

30

我不确定是不是使用范围不正确,但我有一个脚本可以捕获链接点击并在转到链接页面之前使页面淡出。但是,如果链接是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>


你可以看到,我正在尝试检查链接是否具有 onclick 属性,如果存在,则调用 onclick 函数。我该如何实现?

2个回答

112

使用$(this).attr而不是this.attr

这会将其强制转换为jQuery的上下文环境。


2
我也以为这个方法会有效,但是使用它时却出现了 $(this).attr("onclick").val is not a function 的错误。 - chaoskreator
2
在这种情况下,您不需要使用.val()。 - Diodeus - James MacFarlane

10
尽管Diodeus的说法是正确的,你需要在使用attr()之前将this包装在jQuery集合中(它是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);
    }
});

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

太棒了。像魔法一样好用。我理解使用 call() 比 eval() 更安全,对吗? - chaoskreator

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接