使用 jQuery 获取目标文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14720807/
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
Use jQuery to get text of target
提问by Charles Wyke-Smith
Trying to get the text of an event's target element from an unordered list
尝试从无序列表中获取事件目标元素的文本
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
with code like this
用这样的代码
$('ul').click(function() {
theEl=(event.target.text);
});
When I console log
当我控制台日志
event.target
it returns
它返回
<li>Item 1</li>
and
和
event.target.text
事件目标文本
returns undefined
返回未定义
I just want 'Item 1'. I know I have done this before - it must be late...thanks for any assistance :)
我只想要“项目 1”。我知道我以前做过这件事 - 一定迟到了......感谢您的帮助:)
回答by JeffB
Use jQuery's text function:
使用 jQuery 的 text 函数:
$(event.target).text()
回答by Niet the Dark Absol
You're confusing raw JS and jQuery.
你混淆了原始 JS 和 jQuery。
In jQuery, you'd use $(event.target).text()
在 jQuery 中,你会使用 $(event.target).text()
However, it's much more efficient in JavaScript: event.target.firstChild.nodeValue
但是,它在 JavaScript 中效率更高: event.target.firstChild.nodeValue
EDIT: Here's a JSPerfas proof.
编辑:这是一个JSPerf作为证明。
回答by Travis J
The reason event.target.text
is undefined is because HTMLElement does not have that method or property defined. However, jQuery does have text()
which is what you were looking for. In order to access jQuery methods or properties, you need to wrap the current HTMLElement in a jquery object. This is done by passing it to jQuery, who then creates a function object with it, and the jQuery prototype which exposes the API.
原因event.target.text
未定义是因为 HTMLElement 没有定义该方法或属性。但是,jQuery 确实具有text()
您正在寻找的功能。为了访问 jQuery 方法或属性,您需要将当前的 HTMLElement 包装在一个 jquery 对象中。这是通过将它传递给 jQuery 来完成的,jQuery 然后用它创建一个函数对象,以及暴露 API 的 jQuery 原型。
jQuery(element);//in general
$(event.target).text();//for your situation
回答by kahonmlg
event.target.textContent
It is javascript access too. I recommend to you execute 'Chrome' (or Firefox) javascript console with Ctrl+Shift+J
. Write in your code: console.log(event)
and watch the out on console. You can watch every attribute of object.
它也是 javascript 访问。我建议您使用Ctrl+Shift+J
. 写入您的代码:console.log(event)
并在控制台上观看。您可以查看对象的每个属性。
回答by Karthik Sagar
Try this -> event.target.innerText
试试这个 -> event.target.innerText