我有两个具有不同ID的输入框。只有在输入框之外单击时,才需要调用模糊功能。

尝试以下代码

$('#voc1,#voc2').on('blur', function (e) {

    console.log("calling on blur1111");

});


但是在单击其他输入框时会调用模糊功能。谁能帮我这个。

最佳答案

您可以在事件上使用relatedTarget来检查哪个元素导致第一个元素失去焦点。请注意,relatedTarget可以为空,具体取决于正在发生的事情,因此您需要首先进行检查。然后,您可以查看id并查看它是否是您的输入之一。



$('#voc1,#voc2').on('blur', function (e) {
  let id;
  if (e.relatedTarget) {
    id = e.relatedTarget.id;
  }
  if ((id == 'voc1') || (id == 'voc2')) {
    console.log(`Doing nothing because ${id} was clicked.`);
  } else {
    console.log('Something else was clicked so do something.');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='voc1' /><input type='text' id='voc2' />

07-24 09:44
查看更多