How to get the text value of a clicked link?

∥☆過路亽.° 提交于 2019-12-17 16:31:18

问题


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.


回答1:


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

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



回答2:


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:

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



回答3:


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

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

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



来源:https://stackoverflow.com/questions/4871389/how-to-get-the-text-value-of-a-clicked-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!