开发者

Jquery onclick event

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


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:

  • bind
  • click
  • $


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>


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!


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜