[英]Jquery/Javascript how to change button click function based on select option in dropdown menu?
I have a submit button which calls a specific method based on the selected <option>
by the user.我有一个提交按钮,它根据用户选择的
<option>
调用特定方法。 The problem is both the previous and current addEventListener with their corresponding method gets called when I press the submit button.问题是当我按下提交按钮时,前一个和当前的 addEventListener 及其相应的方法都会被调用。 Both function one and two gets executed.
function 一和二都被执行。 I only want to execute functiontwo if the dropdown value is 2 and the user presses the submit button.
如果下拉值为 2 并且用户按下提交按钮,我只想执行 functiontwo。 What am I doing wrong?
我究竟做错了什么?
HTML: HTML:
<select class="div-toggle" id="filter-list" data-target=".my-info-1">
<option value="1" data-show=".1">Option 1</option>
<option value="2" data-show=".2">Option 2</option>
</select>
<button id="submitbutton">Submit</button>
JQuery/JavaScript: jQuery/JavaScript:
I use the if pathname here because I use one general JavaScript file.我在这里使用 if 路径名,因为我使用了一个通用的 JavaScript 文件。 If I declare the eventlistener outside functions I get undefined error on other pages because it can't find the element.
如果我在函数之外声明事件监听器,我会在其他页面上收到未定义的错误,因为它找不到元素。
var btnsubmit = document.getElementById("submitbutton");
if (window.location.pathname=='/test/testpage.html') {
$('#filter-list').on('change', function() {
if(this.value == '1'){
btnsubmit.addEventListener('click', functionOne);
} else if(this.value == '2'){
btnsubmit.addEventListener('click', functionTwo);
}
});
Instead of your method you can choise which function on button click base to select value like:而不是您的方法,您可以选择 function 按钮单击基础上的 select 值,例如:
document.querySelector('#submitbutton').addEventListener('click', () => { var valueSelect = document.querySelector('#filter-list').value; if (valueSelect === '1') { functionOne(); } else { functionTwo(); } }); function functionOne(){ console.log('one'); } function functionTwo(){ console.log('two'); }
<select class="div-toggle" id="filter-list" data-target=".my-info-1"> <option value="1" data-show=".1">Option 1</option> <option value="2" data-show=".2">Option 2</option> </select> <button id="submitbutton">Submit</button>
You need to unsubscribe from the previously set EventListener
.您需要取消订阅之前设置的
EventListener
。
Something like this:像这样的东西:
if (this.value == '1') {
btnsubmit.addEventListener('click', functionOne);
btnsubmit.removeEventListener('click', functionTwo);
} else if (this.value == '2') {
btnsubmit.addEventListener('click', functionTwo);
btnsubmit.removeEventListener('click', functionOne);
}
You can try something like this你可以试试这样的
$('#submitbutton').on('click', function() {
if (window.location.pathname=='/test/testpage.html') {
if($('#filter-list').val() == '1'){
functionOne();
} else if($("#filter-list").val() == '2'){
functionTwo();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.