簡體   English   中英

觸發定義onclick事件的當前元素

[英]Trigger current element where onclick event is define

我有這樣的功能。 我想選擇當前元素而不傳遞參數或更改HTML中的任何內容。

我看到$(this)不起作用。 我們還有其他技術可以實現嗎?

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

像這樣的HTML。

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

另一個解決方案是通過<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> 

上下文錯誤,這是窗口對象,而不是您要更改顏色的元素

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