在JavaScript中,下拉菜單功能可以通過以下幾種方式實現:
<select>
和<option>
標簽創建下拉菜單,然后使用CSS樣式來定義下拉菜單的樣式。HTML代碼示例:
<select>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
HTML代碼示例:
<select id="dropdown">
</select>
JavaScript代碼示例:
var dropdown = document.getElementById("dropdown");
// 添加選項
dropdown.options.add(new Option("Option 1", "option1"));
dropdown.options.add(new Option("Option 2", "option2"));
dropdown.options.add(new Option("Option 3", "option3"));
// 監聽選擇事件
dropdown.addEventListener("change", function() {
var selectedOption = dropdown.options[dropdown.selectedIndex];
console.log("Selected option: " + selectedOption.value);
});
jQuery代碼示例:
$("#dropdown").change(function() {
var selectedOption = $(this).val();
console.log("Selected option: " + selectedOption);
});
React代碼示例:
import React, { useState } from "react";
function Dropdown() {
const [selectedOption, setSelectedOption] = useState("");
const handleSelect = (event) => {
setSelectedOption(event.target.value);
console.log("Selected option: " + event.target.value);
};
return (
<select onChange={handleSelect}>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
);
}
export default Dropdown;
以上是一些常見的實現下拉菜單功能的方法,具體選擇哪種方式取決于你的項目需求和技術棧。