Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

object - jQuery: this.attr() not a function?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

This forces it into the context of jQuery.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...