简体   繁体   中英

How to get text/val from a list of things using Jquery

I have customized the wp_get_archive added a class="tlyear" to its tag.

and using jquery to get each of the years

var y = jQuery('.tlyear');
var m = jQuery('.tlyear').text();
jQuery('.tlyear').click(function() {
  alert(m);
});

when I click on one of the it supposes to return the alert text as 1955 but instead, it returns me a whole string of years as "19481955". How do I get the years only from the I click on? since all the has the same class.

在此处输入图片说明

You want to get the text of the just the clicked item, so make use of this , which refers to that item:

 jQuery('.tlyear').click(function() { alert(jQuery(this).text()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="tlyear"><a href="#">1948</a></div> <div class="tlyear"><a href="#">1955</a></div> <div class="tlyear"><a href="#">1963</a></div> 

(Or it may make sense to use jQuery(this).find('a').text() , because you're binding the click handlers to the containing divs, not to the anchor elements that have the text you want, though it doesn't really matter if there are no other elements within those divs.)

In your code, this line:

var m = jQuery('.tlyear').text();

...gets the text of all of the matching elements with no relation to which one(s) might later be clicked on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM