简体   繁体   中英

Display title attribute as string in another HTML element

Been trying everything all day to get this to work with no luck.

I want to use the title attribute from an li element as a string inside of a completely separate span element.

Here is my code:

<script type="text/javascript">
    $(document).ready(function(){

    });
</script>
<div id="slider">
  <ul>
    <li class="slide" title="Careers">
        <img src="large-image-1.jpg" alt="Large Image 1" /> </li>
  </ul>
</div>
<div id="slide-thumbs">
  <ul>
    <li><img src="thumb-image-1.jpg" alt="Thumbnail for Large Image 1" />
        <span class="thumb-caption"><!-- need title attribute above reading "Careers" to go here --></span>
  </ul>
</div>

I feel like I'm missing something easy here. I can only use Javascript to do this with the script I'm working with. PHP is not an option. Any help would be very much appreciated.

Thank you, Justin.

var title = $('.slide').attr('title');
$('span').html(title);

The JS should work fine, but something to consider is you could do this with pure CSS and avoid the extra markup. Just display the title attribute using a pseudo-element and position it where you like:

.slide:before {
    content: attr(title);
    position: absolute;
    display: block;
}

Since the title is already displaying on the page and you're not generating anything else in addition to it, no reason for the extra element

If there is more than one slide, better use:

$('.thumb-caption').each(function(i) {
    $(this).html($('.slide').eq(i).attr('title'));
});

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