Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - starting with element passed into function via this pointer

Tags:

jquery

I am very new to jQuery so this may be a really stupid question. :-) I'm trying to get something like the following working:

<html>
<head>
    <title>JQuery test</title>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("jquery", "1"); // Load jQuery

      function DoSomething(link)
      {
        $(link).after('<div>hello world!</div>');
      }
    </script>
</head>
<body>
    <a href="javascript: DoSomething(this);">Click!</a>
</body>
</html>

Right now that doesn't seem to do anything. But if I change the line to:

$('a').after('<div>hello world!</div>');

Then a DIV does get inserted. However, I want to use an element passed into the function to control where the element gets inserted. Basically, I can't figure out how to start a jQuery query based on an element passed in to a function via the "this" pointer.

Thanks for the help,

~ Justin

like image 606
RationalGeek Avatar asked Mar 24 '26 23:03

RationalGeek


1 Answers

With jQuery, you can generally avoid inserting any javascript into your HTML at all, eg: href="javascript: ..." or href="#" onclick="...". A neater way is to write a query to target that element and apply the behaviour from there. The simplest way to target the element is to give it an ID, but you could use any method you like.

<a href="#" id="myLink">Click!</a>

and your jQuery:

$('#myLink').click(function() {
    $(this).after("<div>hello world!</div>");
});

Inside the event handling functions, this refers to the DOM element that was targeted by the event.

If you want to get a jQuery object from an element - just pass it to the constructor:

$(domElement)

You might be having issues because of the way you're calling the handler. Try changing your link to this style:

<a href="#" onclick="doSomething(this)">

Just remember to make doSomething() return false

like image 186
nickf Avatar answered Mar 27 '26 11:03

nickf