2015-05-11 41 views
2

我有一個加載了iframe的onclick事件。我需要能夠動態更改onclick偶事件中的部分URL。什麼是最好的方式來做到這一點?我需要動態替換的部分在下面突出顯示爲****變量***。將動態變量添加到onclick事件

var ****variable here*** = '343h343432e'; 

<button type="button" id="load_2" class="btn btn-info" onClick="document.getElementById('attri_map').height = '520';document.getElementById('attri_map').src='https://example.com/****variable here***';document.getElementById('load_2').style.display = 'none';">Click to Load</button> 

<iframe id='attri_map' width='100%' height="0" frameborder='0' allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe> 
+0

一旦你想改變的變量名稱或其內容 – Waqas

+0

爲什麼不你不使用變量名和它的值使用一個鍵/值對對象var varName = {key:「urlPart」,data:{其他任何東西}} – TomSlick

+0

不使用var請嘗試 – Waqas

回答

2

這是一個很好的機會讓你提取出JavaScript,因爲內聯並不是很好的做法。

你的元素在你的HTML中刪除onClick事件,那麼你可以這樣做:

(我也把attri_map到變量去除重新查詢相同元素的DOM開銷。)

var variable = "example"; 

document.getElementById("load_2").onclick = function() { 
    var attrMap = document.getElementById('attri_map'); 
    attrMap.height = '520'; 
    attrMap.src='https://example.com/' + variable; 
    document.getElementById('load_2').style.display = 'none'; 
}; 
+0

謝謝。這是我正在尋找的方向。我知道有比這更好的方法來做到這一點。您的更改工作完美。也欣賞額外清理! – jonmrich

+0

@jonmrich沒問題,很高興我能幫忙。 – mattytommo

1

****這裏變量*** ='343h343432e';

其實,如果你不變量之前寫「VAR」你可以改變它隨時whereevery你是我認爲你需要嘗試