简体   繁体   English

防止在javascript中触发父级的同级事件

[英]Prevent parent's sibling's event from triggering in javascript

<input id="test" type="text" list="list">
<datalist id="list">
    <option value="A">First option</option>
    <option value="B">Second option</option>
</datalist>
$("input").keyup(function(event) {
    //any event like this for example...
    console.log(event.target.value);
});

I don't want this event to trigger after the user clicked on an option. 我不希望用户单击选项后触发此事件。 Already tried the followings even though it was unlikely to work (javascript) : 即使不太可能正常工作(javascript),也已经尝试了以下方法:

$("option").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
});

Also why does the event trigger since I used a keyup event and not an input ? 另外,为什么由于我使用了keyup事件而不是input事件而触发了该事件? ... ...

Do with Keypress . Keypress

UPDATED 更新

you need to call the value from the event inside not a onload 您需要从事件中调用值而不是onload

 $("input").keypress(function(event) { //any event like this for example... console.log("Hello from the other side"); }); $('#test').change(function(){ // you need to call the value from the event inside not a onload console.log(document.getElementById("test").value) //no need console.log($(this).val()) // jquery alredy present so simple use that }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="test" type="text" list="list"> <datalist id="list"> <option value="A">First option</option> <option value="B">Second option</option> </datalist> 

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

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