Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
chaoskreator Avatar asked Feb 06 '12 17:02

chaoskreator


People also ask

What is attr() in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How to get attribute values in jQuery?

The jQuery attr() method is used to get attribute values.


1 Answers

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

This forces it into the context of jQuery.

like image 92
Diodeus - James MacFarlane Avatar answered Nov 16 '22 04:11

Diodeus - James MacFarlane