2015-10-13 66 views
0

我有一個按鈕Add Filter,當下拉列表中的值Choose table發生更改時,我將動態創建該按鈕。我在JavaScript中添加了onklick atttribute Add Filter,我想將參數傳遞給它。但是,當我通過filterButton.onclick=addFilter(db);傳遞參數時,即使在單擊它之前,它也會執行addFilter(),即使db的值正確傳遞。如果我給filterButton.onclick=addFilter();並嘗試將db作爲this.dbdb作爲全局變量訪問,它將分別打印未定義和空值。未將值傳遞給動態創建的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> 

回答

0

一種選擇是:

... 
// filterButton.onclick=addFilter(db); 
filterButton.onclick = (function(current_db) { 
          return function() { 
           addFilter(current_db); 
          }  
         })(db); 
... 

JSFiddle demo

相關問題