Jquery onclick事件

时间:2011-02-21 16:49:32

标签: javascript jquery

我有一个链接

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

是否可以在onclick部分使用Jquery并将某些内容应用于当前元素?

类似于:

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

更新:

  • 我想点击
  • 后更改内容
  • 我更喜欢使用$this,所以我不依赖于id

4 个答案:

答案 0 :(得分:1)

是的,有可能:

<a href='whatever' onclick='$("#special_link").html("test");'>blah</a>
但是,这很少是必要的。通常,您可以稍后使用选择器来查找a元素并使用bindclick来挂钩处理程序,例如:

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)
    });

});

如果special_link是您要执行此操作的链接的id(我不确定,从您的问题中),您可以简化:

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)
    });

});

更多:

答案 1 :(得分:0)

您提供的代码将在onclick属性中按原样运行,如T.J.克劳德指出。你的问题是使用jQuery作为当前元素吗?像这样:

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

答案 2 :(得分:0)

您可以将当前元素称为this

示例:

<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>

请不要使用onclick,依赖更通用且无阻碍的绑定。

祝你好运!

答案 3 :(得分:0)

如果你想要内联,并且它就像更改HTML一样简单,我可能不会使用jQuery。

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

示例: http://jsfiddle.net/8ucGB/2/

相关问题