简体   繁体   中英

Jquery show img title in span

I want to show the image title in a span tag. I use this code, but there has nothing showing in the span tag.

<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
jQuery(document).ready(function( {
$('#thumb ul li a img').fadeIn(function() {
        var $this = $(this);
        $this.next('.showtitle').append($this.attr('title'));
    });
});
</script>
...
<div class="thumb"  id="thumb">
<ul class="ul">
<?php
$result = mysql_query("SELECT * FROM ..."); 
$strstr=1; 
while ($row = mysql_fetch_array($result))
{
echo '<li class="li"><a href="' . $row['link']. '"><img src="'.$row['image'].'" title="'.$row['title'].'" class="img'.$strstr.'" /></a><span class="showtitle" /></li>';
$strstr++;
}
?>
</ul>
</div>

I have checked, the title is not empty in the database. How do I fix it?

The problem is that .next() from your <img> element will be empty - it's the last (only) thing in its surrounding <a> tag. Try

$this.closest('a').next('span.showtitle').text($this.attr('title'));

Try this change:

$('#thumb ul li a img').fadeIn(function() {
        var $this = $(this);
        $this.parent().next('.showtitle').append($this.attr('title'));
    });
});

I added in the .parent() . Yours is grabbing the "next" after the image, but the image is nested inside a link, and the title span follows that link, not the image.

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