0
我有一個按鈕Add Filter
,當下拉列表中的值Choose table
發生更改時,我將動態創建該按鈕。我在JavaScript中添加了onklick atttribute Add Filter
,我想將參數傳遞給它。但是,當我通過filterButton.onclick=addFilter(db);
傳遞參數時,即使在單擊它之前,它也會執行addFilter(),即使db
的值正確傳遞。如果我給filterButton.onclick=addFilter();
並嘗試將db作爲this.db
或db
作爲全局變量訪問,它將分別打印未定義和空值。未將值傳遞給動態創建的onclick函數
我想要做的是,當我點擊按鈕Add Filter
並執行addFilter(db)
,它應該得到選定數據庫的值,即選定的下拉列表。我究竟做錯了什麼?
這裏是你可以嘗試JSFiddle
<!DOCTYPE html>
<html>
<body>
<script>
function get_ids(db){
//return ids;
}
function clearDivs(){
//Clears view
}
function chooseTable(db) {
clearDivs();
var div = document.getElementById("table");
var ids=get_ids(db);
var parentElement = document.getElementById('ids');
//adding checkboxes (removed here for simplicity)
var filter = document.getElementById('filter');
var filterButton=document.createElement('input');
filterButton.type='button';
filterButton.value='Add Filter';
filterButton.onclick=addFilter(db);
filter.appendChild(filterButton);
}
function addFilter(db){
window.alert(db);
}
</script>
<center>
<div id="main1">
<div>
Choose Table:<br/>
<select id="table" name="table" onchange="chooseTable(this.value)">
<option name="choice" value=""></option>
<option name="choice1" value="hr.employee">Employees</option>
<option name="choice2" value="account.account">Accounts</option>
<option name="choice3" value="hr.holidays">Holidays</option>
<option name="choice4" value="account.voucher">Account Vouchers</option>
</select>
</div>
</div>
</center>
<div id="ids"></div>
<center>
<br/><br/><br/><br/>
<div id="filter"></div>
<br/><br/><br/><br/>
<input type="button" id="clicking" value="Get result" onclick="getResults();"/>
<div id="check1"></div>
</center>
</body>
</html>