admin管理员组

文章数量:1420181

How do I get the value of the clicked link?

This is my html:

<div id="results">
   <ul>
       <li>
          <a href="">1</a>
      </li>
      <li>
          <a href="">2</a>
      </li>
   </ul>
</div>

This is how I attempted to get the value:

$('#results').on('click', 'a', function (){
   var text = $(this).innerHTML;
});

What am I missing? Is there a better way to do this?

Thanks in advance :)

How do I get the value of the clicked link?

This is my html:

<div id="results">
   <ul>
       <li>
          <a href="">1</a>
      </li>
      <li>
          <a href="">2</a>
      </li>
   </ul>
</div>

This is how I attempted to get the value:

$('#results').on('click', 'a', function (){
   var text = $(this).innerHTML;
});

What am I missing? Is there a better way to do this?

Thanks in advance :)

Share Improve this question asked Feb 10, 2014 at 13:02 DumisaniDumisani 3,0481 gold badge31 silver badges40 bronze badges 1
  • 1 Why are people downvoting this ? – ShrekOverflow Commented Feb 10, 2014 at 13:27
Add a ment  | 

3 Answers 3

Reset to default 6

You're trying to call a native DOM property on a jQuery element.

Use html() or text() if you use the jquery element, not innerHTML, or use this.innerHTML :

$('#results').on('click', 'a', function (){
   var text = this.innerHTML;
});

Using text() would clean the string from the HTML artifacts, so it's probably what you need.

$('#results').on('click', 'a', function (){
   var text = $(this).text();
});

you can use the following.

$('#results').on('click', 'a', function (){
   var text = $(this).html();
});

本文标签: Get the text of the clicked link using javascriptjqueryStack Overflow