jQuery 如何获取点击链接的文本值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4871389/
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-26 18:05:17  来源:igfitidea点击:

How to get the text value of a clicked link?

jqueryjquery-selectors

提问by 95slug

I have matching text in different parts of a document. The first is a set of "tags" in a table like so:

我在文档的不同部分有匹配的文本。第一个是表中的一组“标签”,如下所示:

<div id="my-div">
  <div><a href="#">tag 1</a></div>
  <div><a href="#">tag 2</a></div>
</div>

Then in several other parts of the document, I have a hidden element after the items I want to highlight when the matching link is selected like so:

然后在文档的其他几个部分,在选择匹配链接时要突出显示的项目后面有一个隐藏元素,如下所示:

<div class="hide-me">tag 1</div>

Then my click function is like this:

然后我的点击功能是这样的:

$('#my-div a').click(function() {
  var txt = $(this).text();
  console.log(txt);
});

The output is an empty string, but I'm not sure why.

输出是一个空字符串,但我不知道为什么。

回答by Umair Jabbar

your code seems to be correct, try this one too.

你的代码似乎是正确的,也试试这个。

$('#my-div a').click(function(e) {
  var txt = $(e.target).text();
  console.log(txt);
});

回答by Jakub Konecki

In your case I wouldn't use the text of the link, as it's possible it may change in the future (ie. you need to translate your website). The better solution is to add custom attribute to links:

在您的情况下,我不会使用链接的文本,因为将来它可能会发生变化(即您需要翻译您的网站)。更好的解决方案是向链接添加自定义属性:

<div id="my-div">
  <div><a href="#" sectionId="someId1">tag 1</a></div>
  <div><a href="#" sectionId="someId2">tag 2</a></div>
</div>

And then put the id of the hidden tag there, so you and up with:

然后把隐藏标签的 id 放在那里,这样你就可以了:

$('#my-div a').click(function() {
  var sectionId = $(this).attr('sectionId');
  $('#' + sectionId).show();
  return false; // return false so the browser will not scroll your page
});

回答by Abhishek Mehta

$('#my-div a') is ambiguous.

$('#my-div a') 不明确。

It goes to read all the a tags within '#my-div'

它会读取“#my-div”中的所有 a 标签

U need to specify which of the 2 tags is clicked..

您需要指定单击了 2 个标签中的哪一个。