2016-11-10 154 views
0

我有一個顯示一個隨機圖像這個小腳本,它是回聲ALT屬性:隨機圖像

<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.jpg007.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>

我這樣做是正確的,這是正確的方式走?就像我說的,我不擅長編碼,所以謝謝你的幫助。

回答

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'); 
     } 
    }); 

它只是一個想法,你需要對其進行修改以滿足您的特定問題。祝你好運。 我希望它有幫助

+0

謝謝!圖像顯示一個人的臉。我想在'H2'標籤下的圖像下添加名稱(我猜測使用ALT是最好的選擇)。我希望清除一些東西... – Steggie

+0

我更新了答案,我希望你可以使用它爲你的condition.Try並告訴我,如果它的任何問題。 – Learner

+0

這每次刷新時都會顯示一張隨機圖像? – Steggie

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']; ?>"> 
+0

感謝您的快速回復,但您確定此代碼是正確的嗎?如果我將它添加到我的頁面中,它會中斷(空白屏幕...) – Steggie

+0

@Steggie:現在就試試,我在代碼中添加了缺少的分號。如果您運行的是舊版本的PHP(5.3或更高版本),則可能會出現問題,因爲這些版本不支持短陣列語法。 –

+0

仍然變黑屏。我可以把這個代碼放在任何地方?即使我在我的頁腳中加載我的jQuery。這對PHP應該很重要,對吧?我查了一下,我的服務器運行的是PHP版本5.3.29。我不能改變這個...我的託管服務提供商不這樣做......這是一個真正的問題? – Steggie