Get contents of php created div with variable id with JQuery
On my page I have a search form which generates a table for the results. In that table, each cells content is surrounded by a span tag with an ID based on the cells name and rows ID in the database. In addition the span gets a fixed class. Heres a printed example:
<td><span id="firstname_203" class="text">John</span></td>
What I am trying to do, is that when I hover the cell that contains the firstname, I want the firstname to appear on a different part of the page. I have tried the code below, but it only returns firstname=null:
( function($) {
$(document).ready(function()
{
$(".text").hover(function()
{
var ID=$(this).attr('id');
var firstname=$("#firstname_"+ID).html();
$($(".firstname")).html("firstname="+firstname);
});
});
} ) ( jQuery );
It's the ID part that doesn't work because if i hardcode the ID (e.g. "#firstname_203") it works just fine.
When I think about it, the only thing I need to know is how to get the php generated integer following the开发者_如何学运维 ID.
Update:
When adding more variables (this).text didn't work as it returned the whole rows values. Instead I had to use this:
$("#table td:nth-child(1)").hover(function(event){
and return the cells as:
var firstname= $td.eq(0).text();
and so on.
You can just skip the whole Id kerfuffle and go straight to the .html()
.
(function($) {
$(document).ready(function() {
$(".text").hover(function() {
var firstname = $(this).html();
$(".firstname").html("firstname=" + firstname);
});
});
})(jQuery);
Also, you could probably just get away with using .text()
EDIT:
Given this html
<div class="userDetails">
<span class="fname">Barry</span>
<span class="lname">Smith</span>
</div>
<div class="firstname">Firstname</div>
<div class="lastname">Lastname</div>
You could do:
(function($) {
$(document).ready(function() {
$(".userDetails").hover(function() {
var firstName = $('.fname', this).text();
var lastName = $('.lname', this).text();
$(".firstname").html("firstname=" + firstName);
$(".lastname").html("lastname=" + lastName);
});
});
})(jQuery);
I've created a jsFiddle for you - http://jsfiddle.net/HZRSW/
精彩评论