在前面的示例中,我通过 ID 明确捕获每个单击的列表项,这不实用且高效,特别是对于太多项目。我想要实现的是动态获取它,而不需要对所有列表项进行硬编码。
$(function() {
$("#a1").click(function()
{
document.getElementById("dropdown").innerHTML = "A-1";
document.getElementById("result").innerHTML = process("a1");
});
$("#a2").click(function()
{
document.getElementById("dropdown").innerHTML = "A-2";
document.getElementById("result").innerHTML = process("a2");
});
$("#a3").click(function()
{
document.getElementById("dropdown").innerHTML = "A-3";
document.getElementById("result").innerHTML = process("a3");
});
});
function process(param)
{
// Some processing!
return param;
}
最佳答案
要使用现有代码,请尽可能少地更改它,您可以绑定(bind)到 ul.dropdown-menu li
并从其中的 a
获取 HTML并使用当前 (this
) li
的 id
值,类似于:
$("ul.dropdown-menu li").click(function() {
var $link = $(this);
document.getElementById("dropdown").innerHTML = $("a", $link).html();
document.getElementById("result").innerHTML = process(this.id);
});
DEMO - 用单击事件替换多个
关于jquery - 获取被点击的列表项的ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14637029/