2016-03-28 163 views
2

我正在使用google maps API。我的HTML看起來像這樣:執行Jquery函數的兩個條件()

<form id="searchTheme" method="get"> 
    <select class="form-control" name="thema" id="themaID"> 
      <option value="1">item1</option> 
      ... 
      <option value="5">item1</option> 
    </select> 
    <input type="submit" name="submit" value="zoek"> 
</form> 

<button id="allePois"> Alle POI&lsquo;s</button> 

我的JavaScript(jQuery的)看起來像這樣:

function initMap(x) { 
    //some other code 
    var controlUIMijnPOIS = document.getElementById('allePois'); 

    $('#searchTheme').submit(function() { 
     //CODE to be executed (with the themaID passed by the form) 
    }) 

    controlUIMijnPOIS.addEventListener('click', function() { 
     //CODE to be executed (same code as above but themaID has no value, wich is fine) 
    }) 
    //some other code 
} 

我可以複製兩個事件的代碼(表單提交和按鈕點擊),但我想的一樣如果提交表單或點擊按鈕,則執行代碼。 (我不希望有一大堆的代碼兩次我的腳本)

所以我會得到這樣的事情:

$('#searchMyTheme').submit || controlUIMyPOIS.addEventListener('click') function(){ 
    //CODE to be executed. 
} 

是,即使是可能的,如果是這樣,我怎麼能建立這個?

+0

你能解釋得更清楚嗎, – mmativ

+0

請儘量放html代碼,以及試圖運行什麼函數。 – mmativ

+0

你想將2個事件附加到同一個監聽器?這似乎是正常的事情。你面臨什麼問題? – avck

回答

2

定義一個函數並在您的事件處理函數上調用它。

function your_func(){ 
... 
} 

$('#searchMyTheme').on('submit',your_func); 
controlUIMyLocation.addEventListener('click',your_func); 

當一個不存在另一個禮物,將不會有問題。

+0

這解決了它。謝謝。 – Rob