開發者嘗試動態設置圖片 src:
// 錯誤代碼
var PicturePath = "S3Media/photo.jpg";
var url = "https://localhost:56809/" + PicturePath; // 本意:拼接完整路徑
img.src = url;
// 實際請求:https://localhost:56809/S3Media/PicturePath (字面量 "PicturePath" 被當作路徑一部分)
瀏覽器報錯:Failed to load resource: 404 (Not Found),請求 URL 顯示字面量 PicturePath 而非變量值。
開發者可能寫成了類似以下形式(推測):
// 錯誤寫法示例
var url = "https://localhost:56809/" + "PicturePath"; // 缺少變量引用,或模板字符串語法錯誤
// 或
var url = 'https://localhost:56809/' + PicturePath; // 若 PicturePath 未定義則為 "undefined"
核心問題:JavaScript 中變量名不能直接放在字符串字面量內部,必須通過 + 運算符或模板字符串 ${} 明確拼接。
var PicturePath = "S3Media/photo.jpg"; // 假設來自後端或輸入
var baseUrl = "https://localhost:56809/";
var fullUrl = baseUrl + PicturePath; // 正確:變量在引號外
img.src = fullUrl;
const PicturePath = "S3Media/photo.jpg";
const fullUrl = `https://localhost:56809/${PicturePath}`;
img.src = fullUrl;
// 後端已返回完整 URL
img.src = PicturePath; // 直接賦值
PicturePath 確認變量值。"https://localhost:56809/" + PicturePath 觀察拼接結果。img.src 實際值與 Network 面板請求 URL。
function buildImageUrl(relativePath, base = 'https://localhost:56809') {
if (!relativePath) return '/static/images/placeholder.png';
// 統一處理斜杠,避免雙斜杠或缺失
const cleanBase = base.replace(/\/+$/, '');
const cleanPath = relativePath.replace(/^\/+/, '');
return `${cleanBase}/${cleanPath}`;
}
// 使用
img.src = buildImageUrl(PicturePath);
「變量進引號變字面量」是 JS 新手高頻低級錯誤。牢記:字符串字面量內只有字符,沒有變量。善用模板字符串與 Console 調試,秒級定位拼接問題。