开发者

Get what's in between the anchor tag that 's clicked

开发者 https://www.devze.com 2022-12-15 09:37 出处:网络
If I had something like: <a>Content 1</a> <a>Content 2</a> <a>Content 3</a>

If I had something like:

<a>Content 1</a>
<a>Content 2</a>
<a>Content 3</a>

And I wanted to get the what's in between the anchor tags (the words being clicked), how would I go about that? The links开发者_Python百科 are shown dynamically, so I can't add an id attribute to them. (I think I can't, at least.)


This should work to select all:

$('a').each(function() { $(this).text(); /* do something with it */ });

if you want to get the click event on anchor tags, but only those without an id or class, try this:

$('a').not('a[id]').not('a[class]').click(function() { $(this).text(); ... });

and if you only want your action to be performed once:

$('a').not('a[id]').not('a[class]').one("click", function() { $(this).text(); ... });


You can use any CSS selector that matches these tags to get a jQuery object for them.

You can then use text() to get the contents of a tag in plain text, or html() to get the direct html code, including any nested tags.

Example:

$('a').each(function() {
     alert($(this).text());
});


If the links are actually built dynamically once the page is already served to the client then you will want to wrap your <a> tags with an identifying element and then add an event listener to the wrapping element.

If you want this behavior for all the links on the page, then just use:

$('a').click(
   function() { 
      var link_text = $(this).text();
      //Do something with link_text 
   });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号