這篇要寫的是另一個需求,除了單選的下拉還需要多選的下拉選單,另外使用動態生成,完整程式碼如下:
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script>
function creatMutiDropDowns() {
let values = ['test1', 'test2', 'test3'];
let objDiv = document.getElementById("div1");
//加入主要物件
let dr = document.createElement('button');
dr.id = "dropdows1";
dr.type = "button";
dr.setAttribute("data-bs-toggle", "dropdown");
dr.setAttribute("style", "width=100px;");
dr.classList.add("dropdown-toggle");
objDiv.appendChild(dr);
//按鈕文字或圖片設定
let objSpan = document.createElement('span');
objSpan.innerHTML = "▼";
dr.appendChild(objSpan);
//建立ul
let ul = document.createElement('ul');
ul.classList.add("dropdown-menu", "dropdown-menu-end");
ul.setAttribute("bottom", "auto");
//跑迴圈將資料加入li
values.forEach((val, idx) => {
let li = document.createElement('li');
li.classList.add("dropdown-item");
let objChkbox = document.createElement("input")
objChkbox.id = 'chk_' + idx;
objChkbox.setAttribute("type", "checkbox");
objChkbox.classList.add("check_box");
li.appendChild(objChkbox);
//index值
objChkbox.value = val;
//選項文字
let objSpan = document.createElement('span');
objSpan.innerHTML = val;
li.appendChild(objSpan);
li.addEventListener("click", async (e) => {
//若為多選,阻止事件冒泡,防止觸發li的點擊事件
e.stopPropagation();
let objChk = $(e.currentTarget).children("input")[0].checked;
if (objChk) {
$(e.currentTarget).children("input")[0].checked = false;
} else {
$(e.currentTarget).children("input")[0].checked = true;
}
});
ul.appendChild(li);
});
objDiv.appendChild(ul);
}
</script>
</head>
<body>
<div id="div1">
<button type="button" onclick="creatMutiDropDowns();">creatDropDowns</button>
</div>
</body>
</html>
原本的單選下拉選單因為點選後就回去了,所以這裡使用 e.stopPropagation();
做成點選了也不會關閉下拉選單,阻止事件冒泡,即可選擇其他選項,達到多選的效果。
以上,參考的是這篇文章:使用bootstrap 的下拉菜單實現select的下拉複選框多選
最後附上完成圖: