(function() {
$(".input-msg").focus(function() {
$(".item-list").css('display', 'block');
$(".item-list div").click(function() {
var inputValue = $('.input-msg');
var data = $(this).text();
inputValue.val(data);
});
}).blur(function() {
$(".item-list").css('display', 'none');
});
})();

.input-wrapper {
width: 300px;
}
.item-list {
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Please add your HTML so we can run it -->
<div class="input-wrapper">
<input type="text" class="input-msg" placeholder="click me">
<!-- input msg -->
<div class="item-list">
<div>This is item one</div>
<div>This is item one</div>
<div>This is item one</div>
<div>This is item one</div>
</div>
</div>
&#13;
答案 0 :(得分:0)
此代码未绑定click事件,您正在调用click事件。
$(".item-list div").click()
{
var inputValue = $('.input-msg');
var data = $(this).text();
inputValue.val(data);
}
应该是
$(".item-list div").off('click').click( function () {
var inputValue = $('.input-msg');
var data = $(this).text();
inputValue.val(data);
});
将点击更改为mousedown,它可以正常工作,因为当您单击模糊事件时会触发并导致在单击操作完成之前隐藏列表。
(function() {
$(".input-msg").focus(function() {
$(".item-list").css('display', 'block');
$(".item-list div")
.off('mousedown')
.on('mousedown', function () {
var inputValue = $('.input-msg');
var data = $(this).text();
inputValue.val(data);
});
}).blur(function() {
$(".item-list").css('display', 'none');
});
})();
&#13;
.input-wrapper {
width: 300px;
}
.item-list {
display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Please add your HTML so we can run it -->
<div class="input-wrapper">
<input type="text" class="input-msg" placeholder="click me">
<!-- input msg -->
<div class="item-list">
<div>This is item one</div>
<div>This is item two</div>
<div>This is item three</div>
<div>This is item four</div>
</div>
</div>
&#13;
答案 1 :(得分:0)
我认为您的.click()
语法错误,应采用
.click(function(){
//your code here
})
我已更新您的代码
(function() {
$(".input-msg").focus(function() {
$(".item-list").css('display', 'block');
$(".item-list div").click(function(){
var inputValue = $('.input-msg');
var data = $(this).text();
inputValue.val(data);
})
}).blur(function() {
$(".item-list").css('display', 'none');
});
})();