以下是我的有问题的代码
(function($) {
'use strict';
var button = $('#open_button');
var box = $('#dropdown');
function init() {
eventsInit();
}
function eventsInit() {
box.hide();
button.on('click', open);
}
function open(event) {
if (event.target !== button[0]) {
box.hide();
} else {
box.show();
}
}
init();
})(jQuery);
body,
html {
padding: 0;
margin: 0;
}
#container {
height: 100px;
width: 800px;
margin: 0 auto;
}
h1 {
color: white;
}
#dropdown {
height: 600px;
width: 800px;
background-color: black;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<form action="" id="open_button">
<input type="text" placeholder="Enter the text" />
</form>
</div>
<div id="dropdown"></div>
当我点击输入表单输入元素时,我需要下拉菜单,当我点击外部元素时,我需要关闭它。
我的代码我相信它说,如果点击目标不是按钮,则关闭下拉列表,否则显示。
有人可以解释一下,为什么它不起作用?
最佳答案
(event.target !== button[0])
永远正确。
-
event.target
是<input>
领域。 -
button[0]
是<form>
元素。
您可以将 #open_button id 移动到输入字段,这会导致当用户单击输入字段时出现该框 - 但该框永远不会消失(因为您的 if
条件永远不会返回 true。 )
你真正想要的是focus
和blur
输入字段上的处理程序,分别显示和隐藏该框:
$('#open_button input').on('focus', function() {
$('#dropdown').show()
}).on('blur', function() {
$('#dropdown').hide()
});
// added to answer per comment below:
$('#dropdown').on('mousedown',function(e) {
e.preventDefault() // prevent input field from losing focus when user clicks inside the box
});
$('#dropdown').hide();
#dropdown {
height: 600px;
width: 800px;
background-color: black;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<form action="" id="open_button">
<input type="text" placeholder="Enter the text" />
</form>
</div>
<div id="dropdown"></div>
关于javascript - 为什么以下 Jquery event.target 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44553771/