简体   繁体   English

触发定义onclick事件的当前元素

[英]Trigger current element where onclick event is define

I have a function like this. 我有这样的功能。 I want to select current element without passing parameter or change anything in HTML. 我想选择当前元素而不传递参数或更改HTML中的任何内容。

I see the $(this) is not working. 我看到$(this)不起作用。 Are there any other techniques we can achieve this? 我们还有其他技术可以实现吗?

function social_follow_us(){
    $(this).addClass("green")
}   

HTML like this. 像这样的HTML。

<a href="..." onclick="social_follow_us()" class="btn btn-primary followButton" target="_blank" id="instagram_follow">Follow on Instagram</a>

Another solution is to pass this from <a onclick="..."> event: 另一个解决方案是通过<a onclick="...">事件传递this

 function social_follow_us(elem) { $(elem).addClass("green") } 
 a.green { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="..." onclick="social_follow_us(this)" class="btn btn-primary followButton" target="_blank" id="instagram_follow">Follow on Instagram</a> 

The context this is wrong it is the window object and not the element you want to change color 上下文错误,这是窗口对象,而不是您要更改颜色的元素

function social_follow_us(){
  $(this).addClass("green")
} 

// try this
function social_follow_us(){
  $(".followButton").addClass("green");
}

// or
$('.followButton').click(function() {
  $(this).addClass('green');
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM