Get content inside a td tag when hovered over
<td>
Some stuff here
<span style="display: none;">sekret stuff here</span>
</td>
How would I go about getting the content of the &开发者_运维百科lt;span>
tag in that td, so that my output would be "sekret stuff here", using jQuery?
I've tried a couple of different things, but couldn't get anything to work. =/.
This will alert the contents of the span
when hovering over the td
, only if the td
has an span
element inside:
$('td').mouseover(function() {
if($(this).find('span').size() > 0) {
// This will alert 'sekret stuff here'
alert($(this).find('span').html());
}
});
Assuming there's just one of these on a page:
$('td span').html();
You may consider using pure CSS, because it is potentially faster.
HTML:
<td>
<a class="magic_link" href="#">Some stuff here
<span>sekret stuff here</span></a>
</td>
CSS:
a.magic_link:link,
a.magic_link:visited {
display: block;
width: 100px;
height: 50px;
}
a.magic_link:link span,
a.magic_link:visited span {
display: none;
}
a.magic_link:hover span {
display: inline;
}
If you want to do something with the contents after its been hovered over the td cell you need to give the td cell an ID.
<td id="mycell">
Some stuff here
<span style="display:none">Sekret stuff</span>
</td>
And then use jQuery to bind a mouseover event and do something with the contents:
var cell = $('#mycell'), span = cell.find('span');
cell.bind('mouseover', function () {
var contents = span.html();
// do something with contents
});
If you've got other td
's on the page that don't contain a span
, you'll probably want to use the :has
selector to make sure you're only binding to td
that has a span
child.
$('td:has(span)').mouseover(function(e) {
var content = $(this).find('span').html(); //or .text() for the plain text
//do something with the content
});
I think you're probably better off giving either the td
or the span
a semantic class though, it'll make the intent of your HTML a bit more obvious. Something like
<td>
Some stuff here
<span class="sekret" style="display: none;">sekret stuff here</span>
</td>
... and modify the selector in the javascript to be something like
$('td:has(.sekret)').mouseover(...
Try this:
$('td').hover(function() {
var c = $(this).children('span');
if (c.length > 0) {
alert($(c[0]).text());
}
});
It will bind an event to every td
on your page, and look for child span
elements, popping up an alert with the contents of the first span
inside the td
. You can replace the alert()
part of the code with whatever you'd like to do with the span
contents. Note that inside that code, this
will refer to the td
element.
精彩评论