![](/img/trans.png)
[英]passing parameter on jQuery onclick function from html onclick event
[英]Passing the “this” from the onclick event into the JQuery
我想從我的錨標記中刪除onclick=togglePass(this)
,並想在jQuery中使用它。 我很困惑如何將this
作為參數發送給jQuery的?
$('elem').click(function());
現在,我嘗試將onclick
替換為以下內容:
$('elem').click(function(){..Some code..});
但不確定如何通過this
。
您不需要顯式地傳遞this
。 this
自動綁定到觸發事件的隱式元素。
請嘗試以下示例:
$(".elem").click(function(){ // this referes to the currently clicked element $(this).toggleClass('blue'); });
.elem{ background: green; width: 200px; height:200px; border-radius: 3px; } .blue{ background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="elem">Container</div>
您不需要在jquery中傳遞它 。 希望該示例對您有所幫助。
$(document).ready(function(){ $(".red").click(function(){ $(this).toggleClass("green"); }); });
.red{ background: red; width: 100px; height:100px; } .red.green{ background: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <div class="red"></div> click to change the color
該文件是當前沒有具體以什么this
是設置為事件處理函數中。 該函數的第一個參數應該是jQuery事件。
function fn(_this, e) {
console.log(
_this /* event */
, this /* `HTMLParagraphElement`
, `e` : `undefined` */
)
}
$("p").on("click", fn);
您不必將附加參數傳遞給函數或.on()
。 this
事件處理程序中應的DOM元素,而不是事件處理程序中的jQuery對象。 如果期望this
是處理程序的第一個參數,則可以使用$.proxy()
,它也提供了一個參數來將參數傳遞給函數
function fn(_this, e) {
console.log(
_this /* `[456]` */
, this /* `{abc: 123}` `e` : `jQuery.Event` */
)
}
$("p").on("click", $.proxy(fn, {abc:123}, [456]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.