繁体   English   中英

如果输入值为“某物”,则将 onclick 添加到按钮

[英]If input value is "something" add onclick to the button

如果输入字段的值为“Greece”或“UK”,则在按钮上添加onclick事件,否则没有onclick事件。

<form class="search-options">
    <input id="test" type="text" value="" />
</form>
<button id="search-button">Search</button>
<script>
    $('.search-options').find("input[value='greece']").each(function(){
        document.getElementById("search-button").onclick = "Suggestion.submit();";
    });
</script>

如果输入值为希腊或英国,则按钮应具有 onclick="Suggestion.submit();"

有谁知道我做错了什么?

您需要将事件侦听器存储为函数:

如果您不需要传递参数,则:

document.getElementById("search-button").onclick = Suggestion.submit;

或者,如果您想传递预定义的参数,请使用以下格式:

document.getElementById("search-button").onclick = function(){Suggestion.submit(argument1, argument2, argumentN)}

代替每个值有不同的回调,你真正想要的是一个单一的回调,然后它会根据值(或调用不同的函数)采取不同的行动。 将此回调添加到每个输入 onclick 事件。

使用 addEventListener click 代替 onclick

 $('.search-options').find("input[value='greece']").each(function(){ document.getElementById("search-button").addEventListener('click',function(){console.log("submitted")}) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form class="search-options"> <input id="test" type="text" value="france" /> <input id="test2" type="text" value="greece" /> <input id="test3" type="text" value="UK" /> <input id="test" type="text" value="spain" /> </form> <button id="search-button">Search</button>

我实际上更喜欢这样使用它:

 document.querySelector('#search-button').onclick = function(){ if(document.querySelector('#test').value == 'Something'){ document.querySelector('form span').innerText = document.querySelector('#test').value; //do more }else{ document.querySelector('form span').innerText = 'cancel click'; return false; } }
 <form class="search-options"> <input id="test" type="text" value="" /> <span></span> </form> <button id="search-button">Search</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM