随机图像的Echo ALT属性

时间:2016-11-10 13:58:55

标签: php jquery html image

我有一个显示随机图像的小脚本,即:

<img src="<?php echo bloginfo('template_url');?>/img/members/00<?php $random = rand(1,7); echo $random; ?>.jpg"alt="[ Random Image ]">

这使得脚本中的图像src src="example.com/images/001.jpg" alt="[ Random Image ]">(1,7)将图像的数量001.jpg添加到007.jpg

现在我想要的是将"[ Random Image ]"更改为"$my_alt"并让它在<h2 class="myAlt">...</h2>标记中显示(回显)图像的alt属性。

我不是编码员,所以我真的不知道如何做到这一点。我相信我首先需要给my_alt一个值。所以我会去:

if {image src="example.com/images/001.jpg" $my_alt = "My first Alt"} else if {image src="example.com/images/002.jpg" $my_alt = "My second Alt"}

然后我想要放置alt的值添加代码: <h2 class="myAlt"><?php echo $my_alt(); ?></h2>

我这样做是否正确,这是正确的方法吗?就像我说的那样,我不太擅长编码,所以感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

我遇到了你的问题。试试看它是否有效:

<!-- I am gonna make a sample template so that you may understand how to use my solution for your specific issue -->
 <div class="imageContainer">
    <img src="something" alt="Image1" />
    <h2 class="myAlt"></h2>
</div>
<div class="imageContainer">
    <img src="something" alt="Image2" />
    <h2 class="myAlt"></h2>
</div>
<div class="imageContainer">
    <img src="something" alt="Image3" />
    <h2 class="myAlt"></h2>
</div>
<div class="imageContainer">
    <img src="something" alt="Image4" />
    <h2 class="myAlt"></h2>
</div>

<script>
$('.imageContainer').each(function(){
    $(this).find('.myAlt').html($(this).find('img').attr('alt'));
});
</script>

它会在每张图片下方显示相应的alt

特定两张图片

// giving alt dynimically
    $('img').each(function(){
        if($(this).attr('src')==='image 001.jpg'){
            $(this).attr('alt','person x');
        }
        else if($(this).attr('src')==='image 002.jpg'){
            $(this).attr('alt','person y');
        }
    });

它只是一个想法,你需要修改它以适应你的特定问题。祝好运。 我希望它有所帮助

答案 1 :(得分:0)

我会创建一个包含所有图像及其 alt 的数组,然后选择其中一个并显示它:

<?php
$images = [
  ['file' => '001.jpg', 'alt' => 'My first alt'],
  ['file' => '002.jpg', 'alt' => 'My second alt'],
  ['file' => '003.jpg', 'alt' => 'My third alt'],
  # add more files below
];
$rand = mt_rand(0, count($images) - 1);
?><img src="<?php echo bloginfo('template_url');?>/img/members/<?php echo $images[$rand]['file']; ?>" alt="<?php echo $images[$rand]['alt']; ?>">