How to get the text value of a clicked link?

2019-01-23 23:43发布

问题:

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..