执行Jquery函数()的两个条件

Two conditions for executing a Jquery function()

本文关键字:两个 条件 Jquery 执行 函数      更新时间:2023-09-26

我正在使用谷歌地图API。我的HTML如下所示:

<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.
}

这可能吗?如果可能,我该如何确定?

定义一个函数并在事件处理程序上调用它。

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

当一个人不在场时,另一个人会在场,不会有任何问题。