我有以下按钮列表
<button class="button button2">Hospital</button>
<button class="button button2">Medical</button>
<button class="button button2">Pharmacy</button>
点击功能最好的是在下面的脚本上替换我的Javascript url(dbexport2.php)
// Change this depending on the name of your PHP or XML file
downloadUrl('dbexport2.php', function(data) {
var xml = data.responseXML;
我想根据按钮点击更改php文件,例如,对于医院来说,它想要“downloadUrl('hospital.php')”用于医疗它想要< EM> “downloadUrl('medical.php”)
答案 0 :(得分:3)
您可以使用value
属性
function handleResponse(data) {
var xml = data.responseXML;
// .. etc
}
var buttons = document.getElementsByClassName('button');
for(var i = 0, j = buttons.length; i < j; i++) {
var btn = buttons[i];
btn.addEventListener('click', function() {
downloadUrl(this.value, handleResponse);
});
}
<button class="button" value="hospital.php">Hospital</button>
<button class="button" value="medical.php">Medical</button>
<button class="button" value="pharmacy.php">Pharmacy</button>
答案 1 :(得分:1)
<button class="button button2" data-url="hospital.php">Hospital</button>
<button class="button button2" data-url="medical.php">Medical</button>
<script>
var downloadButtons = document.querySelector('.button[data-url]'),
numButtons = downloadButtons.length;
if(numButtons){
while(numButtons--) {
if(downloadButtons[numButtons]) {
downloadButtons[numButtons].onClick = function(){
var url = this.getAttribute('data-url');
downloadUrl(url, function(data) { ... }
}
}
}
}
</script>
类似于这种方法的东西,取决于您可用的JavaScript库(或缺少的库)。在调用click事件时添加一个可以在javascript中引用的属性,然后在事件被触发时将其传递给您的函数?
答案 2 :(得分:0)
将您的网址插入data-url。
<button class="button button2" data-url="Hospital.php">Hospital</button>
<button class="button button2" data-url="Medical.php">Medical</button>
<button class="button button2" data-url="Pharmacy.php">Pharmacy</button>
然后进行简单的循环。
document.querySelectorAll('button[data-url]').forEach(item => {
item.addEventListener('click', e => {
let url = item.getAttribute('data-url');
//Your code
downloadUrl(url, function(data) { });
});
});