2014-09-04 103 views
0

下面是我的腳本,它假設根據當地時間向用戶顯示問候消息。我從另一個堆棧溢出答案中得到了腳本,但在替換圖像src時遇到了問題。我收到以下錯誤jQuery - 結合變量和圖像src來替換圖像attr

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8888/neil-wp/imgurl%20+%20second.jpg 


$(document).ready(function() { 
    datetoday = new Date(); // create new Date() 
    timenow = datetoday.getTime(); // grabbing the time it is now 
    datetoday.setTime(timenow); // setting the time now to datetoday variable 
    hournow = datetoday.getHours(); //the hour it is 
    imgselector = $('#greeting-img') 
    imgpath = 'wp-content/themes/neil/img/' 

    if (hournow >= 16.5) { // if it is after 4:30pm 
     imgselector.attr("src","imgpath + goodevening.gif"); 
    } 
    else if (hournow >= 12) { // if it is after 12pm 
     imgselector.attr("src","imgpath + goodafternoon.gif"); 
    } 
    else if (hournow >= 0) { // if it is after midnight 
     imgselector.attr("src","imgpath + goodmorning.gif"); 
    } 
}); 

// Wait for window load 
$(window).load(function() { 
    $(".greeting").delay(2000).fadeOut("200"); 
}); 

這裏是我的HTML

<div class="greeting"> 
    <div class="greeting-inner"> 
    <img id="greeting-img" src=""> 
    </div> 
</div> 

回答

2

imgpath是可變的,使用:

imgselector.attr("src",imgpath + "goodmorning.gif"); 
+0

謝謝Milind!非常感謝 – Jordan 2014-09-04 10:03:33

+0

@Jordan:很高興幫助:) – 2014-09-04 10:04:01

+1

@Jordan接受他的回答,如果其正確:) – 2014-09-04 10:05:05