I have a table generated dynamically that may be represented as follows:
<a class="editlink" id="1" href="#">Entry_1</a>
<a class="editlink" id="2" href="#">Entry_2</a>
<a class="editlink" id="3" href="#">Entry_3</a>
<a class="editlink" id="4" href="#">Entry_4</a>
<a class="editlink" id="5" href="#">Entry_5</a>
I'm unable to get the text of the HREF anchor (ie 'Entry_3' ). The following returns correctly the right index:
var index = $(".editlink").index(this);
but this one returns always the last element of the list:
var item_name = $(".editlink").eq(index).text();
$(this).text() returns nothing
$(a#3).text() returns nothing (remember also that the list is generated dinamically)
Thank you.
I FOUND WHAT'S WRONG but don't know how to fix it:
A LOOP generates the following table with a number of rows:
<tr>
<td><a class="editlink" id="1" href="#">Item_1</a><td>
<td><input type="checkbox" /></td>
<td><a class="delete_review" id="1" href="#"><img src="remove.png"/></a></td>
</tr>
I want to delete the row (that part works) when the user clicks the image (.delete_review):
$(".delete_review").click(function() {
var index = $(".editlink").index(this);
var item_name = $(".editlink").eq(index).text();
alert(item_name);
}
I noticed from the examples you provided that the script works if I call JQuery using the same class of the links (.editlink);
$(".editlink").click(function() {
but not if I use the class of the image:
$(".delete_review").click(function() {
If you're trying to get the text of the anchor that was clicked, from within an event handler, it's:
var item_name = $(this).text();
Side note: Your id
values are valid for HTML5 , but not for HTML4 and more significantly not for CSS ; in CSS, an id
value cannot start with a digit. This is significant because jQuery uses CSS-style selectors for querying DOM elements, so it's best to stick to valid CSS id
values if you're going to use them in selectors.
Try
var item_name = '';
$(document).on("click", "a.editlink", function() {
item_name = $(this).text();
});
Also, I'd recommend something like href="#null"
as href="#"
will jump the user to the top of the page.
要获取第三个链接的文本(它的索引为2
,因为索引是从0开始的):
var item_name = $(".editlink").eq(2).text();
Works fine for me with latest jQuery 1.7 and Chrome !
check jsFiddle: http://jsfiddle.net/2GuhV/
$('#3').html();
I think that should do? :o this gets the html in the div id="3". and why do you use a classname and an id name? you could make it so when you generate the urls they output like this:
<a class="editlink 1" href="#">Entry_1</a>
$('.editlink.1).html();
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.