Javascript 获取触发事件的元素的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10421568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:14:31  来源:igfitidea点击:

Get value of element on which the event fired

javascriptjqueryhtml

提问by mol

Possible Duplicate:
Select inner text (jQuery)

可能的重复:
选择内部文本 (jQuery)

I have a span:

我有一个跨度:

<span class="test"> target_string </span>

And the event, that is fired on click on any element of the page.

以及点击页面任何元素时触发的事件。

$('body').click(function(event){
  if ($(event.target).attr('class') == 'test'){
    alert(???);
  }
}

How can I obtain target_string value?

如何获取 target_string 值?

回答by Rocket Hazmat

Use $(event.target).text()to get the text.

使用$(event.target).text()获得的文本。

回答by Simon Smith

Possibly more efficient to delegate from the body:

从身体委派可能更有效:

$('body').on('click', '.test', function(event){
    alert($(this).text())
});

回答by Selvakumar Arumugam

Try below,

下面试试,

$('body').click(function(event){
  var $targ = $(event.target);
  if ($targ.hasClass('test')){
    alert($targ.text());
  }
}

回答by Brian

Not sure if you plan to work with other elements inside that event handler besides those with a class of test, but this may be more concise:

不确定您是否打算在该事件处理程序中使用除具有测试类的元素之外的其他元素,但这可能更简洁:

$('.test').click(function(event){
    alert($(this).text());
});