2016-03-08 60 views
0

我想在URL更改參數時更改圖像。更改URL中的參數時更改圖像

例如:

http://localhost:8080/h5/informational.html

不顯示任何東西,但是當URL有type =參數,我想說明的圖像?

我有這段代碼,但它不起作用。

var img = new Image(); 
var div = document.getElementById('header'); 
var url = "http://172.18.43.33:58380/launcher/h5/informational/cabecera.html?type="; 
var expansion = url + "expansion"; 
var experiencia = url + "experiencia"; 
if (expansion == true) { 
    img.onload = function() { 
    div.innerHTML += '<img src="' + img.src + '" />'; 
    }; 
} else if (experiencia == true) { 
    img.onload = function() { 
    div.innerHTML += '<img src="' + img.src + '" />'; 
    }; 
    img.src = 'images/experiencia.jpg'; 
} else { 
    //Error 
} 

回答

0

if (location.search.indexOf("expansion") !=-1)是一個更好的測試。

var type = ""; 
if (location.search.indexOf("type=expansion"!=-1) { 
    type="expansion"; 
} 
else if (location.search.indexOf("type=experiencia"!=-1) { 
    type="experiencia"; 
} 
if (type) { 
    document.getElementById('header').innerHTML += '<img src="images/'+type+'.jpg"/>'; 
} 

使用代碼從How can I get query string values in JavaScript?

function getParameterByName(name, url) { 
    if (!url) url = window.location.href; 
    name = name.replace(/[\[\]]/g, "\\$&"); 
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), 
     results = regex.exec(url); 
    if (!results) return null; 
    if (!results[2]) return ''; 
    return decodeURIComponent(results[2].replace(/\+/g, " ")); 
} 

var type = getParameterByName("type"); 
if (type) { 
    document.getElementById('header').innerHTML += '<img src="images/'+type+'.jpg"/>'; 
} 
+0

你需要使用:當字符串不爲空

你總是真可能想這一點 - 現在你正在測試一個字符串的truthy值'location.search'並檢查查詢字符串'類型'檢查[此鏈接](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Zamboney

+0

我可以使用location.href從完整的URL中提取類型。 .search或.href將在這裏工作。其實我刪除了第二個參數,因爲它在功能中設置 – mplungjan

+0

Works!謝謝!! :D –