繁体   English   中英

将onthis事件中的“ this”传递到JQuery中

[英]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.

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