如何使用jQuery获得点击的元素文本? [英] how to get clicked element text using jQuery?
问题描述
我想在jQuery警报中获取clicked元素的文本.见下面的例子 https://jsfiddle.net/pymd4n04/2/
I want to get the text of clicked element in an alert of jQuery. See example below https://jsfiddle.net/pymd4n04/2/
jQuery(".results").click(function() {
event.preventDefault();
jQuery(this).find('h3').click(function() {
var text = jQuery(this).text();
console.log(text.trim());
alert(text.trim());
});
});
但是,当我第一次单击时,将显示为空警报,而当我单击第二次时,将显示该值,但会两次发出警报.并保持增量警报.
But when I click first time, empty alert is shown and when I click 2nd the value is shown but twice alert. and keep increment alerts.
任何帮助将不胜感激.
预先感谢
推荐答案
由于所有链接都嵌入在h3
元素内,因此您可以在jQuery中更具体地检索包含在另一个元素内的所有h3
元素,类名.results
像这样:
Since all of your links are embedded inside h3
elements you can be more specific in your jQuery to retrieve all h3
elements that are inside another element with the class name .results
like so:
jQuery(".results h3").click(function() {
第二,在您的代码中,您正在使用两个单击功能...这不是必需的.上面的代码行..单击类名称为.results
的元素内的h3
元素后,您可以轻松地获取该h3
元素的文本,如下所示:
Secondly, in your code you're using two click functions... which is not necessary. With the line of code above.. once you click on an h3
element inside an element with the class name .results
then you can easily grab the text of that h3
element like so:
jQuery(".results h3").click(function(event) {
event.preventDefault();
var text = jQuery(this).text(); // 'this' refers to the h3 element that you clicked.. not the div with the class .results
alert(text.trim());
});
这里正在工作 JSFiddle .
这篇关于如何使用jQuery获得点击的元素文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!