0

I have a link

<a id="special_link" href="" onclick="" >Link</a>

Is it possible to use Jquery in the onclick part and apply something to the current element?

Something similar with :

$("#special_link").html('test'); 

Update :

  • I want to change the content after click
  • I would prefer using $this so I don't depend on the id
1
  • 1
    Could you clarify your question? Do you want to change the html of the link after click? Commented Feb 21, 2011 at 16:53

4 Answers 4

1

Yes, it's possible:

<a href='whatever' onclick='$("#special_link").html("test");'>blah</a>

It's rarely necessary, though. Usually you can hook these things up later, using a selector that finds the a element and uses bind or click to hook up a handler, e.g.:

jQuery(function($) {  // Function gets run at DOM load time

    $("some_CSS_selector_that_finds_the_a_element").click(function() {
        $("#special_link").html("test");
        return false; // Do this only if you don't want the link followed (which I'm guessing you don't)
    });

});

If special_link is the id of the link you want to do this on (I wasn't sure, from your question), you can simplify that:

jQuery(function($) {  // Function gets run at DOM load time

    $("#special_link").click(function() {
        $(this).html("test");
        return false; // Do this only if you don't want the link followed (which I'm guessing you don't)
    });

});

More:

Sign up to request clarification or add additional context in comments.

Comments

0

The code you provided will work as-is in the onclick attribute, like T.J. Crowder pointed out. Is your problem using jQuery for the current element? like this:

<a href='#' onclick='$(this).html("a test link");'>a link</a>

Comments

0

You can refer to the current element as this.

Example:

<script ...>
    $("#special_link").click(function() {
        console.log(this) // You'll see the HTML element, not wrapped by jQuery
        $(this).html("Bar");
    })
</script>
<a href="#" id="special_link">Foo</a>

Please, don't use onclick, rely on bind that's more generic and unobstructive.

Good luck!

Comments

0

If you want it inline, and it's as simple as changing the HTML, I probably wouldn't use jQuery for it.

<a id="special_link" href="#" onclick='this.innerHTML="some new value";'>click me</a>

Example: http://jsfiddle.net/8ucGB/2/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.