2014-06-17 122 views
0

提前致謝。當img標籤的src屬性中有內容時,我需要顯示文本。我需要一些JS來檢測一個屬性是否有內容,然後如果它有一個p標籤是可見的。我需要根據是否有圖像顯示/隱藏文本

HTML

<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <script type='text/javascript' src="SampleJS.js"></script> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Untitled Document</title> 
    </head> 

    <body> 
    <p id="sponsorText">Now you see me!<img src="" class="sponsorImg" id="sponsorText" /></p> 

    </body> 
    </html> 

JS

var attr = $().attr('src'); 

if (typeof attr !== "" && attr !== false){ 
    alert('no image.'); 
    } 

但在這一點上,我甚至不能讓JS來檢測,並給予警告。

我需要Jscript來檢測是否有一個文件名.jpeg,然後如果有它觸發文本。

+1

看起來你試圖使用jQuery ...你忘了包含jQuery庫嗎? – KevBot

+0

'$()。attr('src');'?添加一個jQuery選擇器,你很好走。我不想發表一個答案,因爲你應該對問題有一個最小的理解,而你不知道。 – Popnoodles

回答

1

首先包含jQuery。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 

其次,創建腳本

$(document).ready(function() { 
    // code here.. 
}); 

第三,你需要提供一個選擇上下工夫。

var attr = $('img').attr('src'); // add img element 

這會現在工作。