有一个获得点击div id的func 需要给下一个func这个id而不是“#dropdown1”
$(function() {
$('.drop-down-input').click(function() {
$elementid = this.id;
$elementid= "#" + elementid;
});
console.log($elementid);
$("#dropdown1").click(function() {
$("#dropdown1 .dropdown-list").show();
});
$("#dropdown1 .dropdown-list li").on('click', function(e) {
e.stopPropagation();
$("#dropdown1 .dropdown-list").hide().siblings().val($(this).html());
});
});
HTML:
<div id="dropdown1" class="styled-input-container drop-down-input">
<input id="simple_2" class="drop-down-select" placeholder="input text" type="text">
<ul class="dropdown-list">
<li>eeee</li>
<li>xxxx</li>
<li>xxxx</li>
<li>xsssxxx</li>
</ul>
</div>
想法是我可以在其他地方再次使用此代码。例如,使用2个具有不同ID的下拉列表
答案 0 :(得分:0)
不要发送ID,在元素中添加一个类。
$('.drop-down-input').click(function() {
$('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection
$(this).addClass('selected');
$(this).find(".dropdown-list").show();
});
然后在下一个函数中,您可以使用选择器查找单击的元素:
$(document).on("click", ".drop-down-input.selected li"), function(e) {
e.stopPropagation();
$('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
});
此方法优于在变量中保存ID的一个好处是,您可以使用CSS向所选元素添加样式。
完整代码:
$('.drop-down-input').click(function() {
$('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection
$(this).addClass('selected');
$(this).find(".dropdown-list").show();
});
$(document).on("click", ".drop-down-input.selected li",
function(e) {
e.stopPropagation();
$('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dropdown1" class="styled-input-container drop-down-input">
<input id="simple_2" class="drop-down-select" placeholder="input text" type="text">
<ul class="dropdown-list">
<li>eeee</li>
<li>xxxx</li>
<li>xxxx</li>
<li>xsssxxx</li>
</ul>
</div>