Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在jQuery/coffeescript中获得clicked元素作为参数吗?_Jquery_Coffeescript_Click_Element - Fatal编程技术网

我可以在jQuery/coffeescript中获得clicked元素作为参数吗?

我可以在jQuery/coffeescript中获得clicked元素作为参数吗?,jquery,coffeescript,click,element,Jquery,Coffeescript,Click,Element,我用CoffeeScript和Mootools编写了这段古老的代码: pleaseDo: "click:relay(#click-me)": @doSomething doSomething: (event, element) => console.log event # shows event console.log element # shows element 我正试图将其重写为jQuery,我想知道在jQuery中获取clicked元素的最佳

我用CoffeeScript和Mootools编写了这段古老的代码:

  pleaseDo:
    "click:relay(#click-me)": @doSomething

  doSomething: (event, element) =>
    console.log event   # shows event
    console.log element # shows element
我正试图将其重写为jQuery,我想知道在jQuery中获取clicked元素的最佳方法是什么

  pleaseDo:
    $("#click-me").on "click": @doSomething

  doSomething: (event, element) =>
    console.log event   # shows event
    console.log element # undefined
我知道我可以使用
event.target
,比如:

  doSomething: (event) =>
    element = event.target
    console.log event   # shows event
    console.log element # shows event

但我不喜欢它的样子。我能否以某种方式将真正的“元素”作为doSomething函数的参数(就像在Mootools中一样)?

您只需执行
$(event.target)
$(this)
您可以这样做:

   $('#click-me').on('click', function(){
     console.log($(this));
   });
这将返回jQuery对象,这样您就可以像这样使用它

   $('#click-me').on('click', function(){
      $(this).text('hola');
    });
否则,如果您希望整个html对象使用javascript

   $('#click-me').on('click', function(){
      console.log(this);
   });

这是唯一的办法吗?它看起来比Mootools中的要糟糕得多(特别是如果我需要在每个函数中重新存储它…)。关键是,event.target返回有效元素,而$(this)返回整个类,知道为什么会发生这种情况吗?@Wordpressor,因为您使用
=>
对类定义了
doSomething
。只有event.target为我返回有效元素,$(这)返回整个类对象,我不确定为什么:(这不会引发错误吗?更新的
请执行
块是没有意义的。