gpt4 book ai didi

javascript - 使用 JQuery .on() 函数为列表中的每个项目添加点击事件

转载 作者:行者123 更新时间:2023-11-30 13:13:25 24 4
gpt4 key购买 nike

我有一个按钮,当单击该按钮时,它会动态地将一个新行插入到表格中。我希望能够从此表中删除行,所以我尝试使用 jQuery 的 .on() 函数将点击处理程序附加到每行末尾的 span 元素... . 效果很好,除了当我单击跨度以删除单个项目时,会为表中的所有项目调用单击事件....它们都被删除了。我如何连接它以便它只调用我在处理程序上单击的行?这是我的代码:

这是js:

$("#milestonesList").on('click', 'span[id*="tempmilestone"]', function (e) {
$(this).each(function () {
$('span[id*="tempmilestone"]').each(function () {
alert("ON: " + $(this).attr("idx"));
_milestones = _milestones.slice(parseInt($(this).attr("idx"), 10));
buildMilestoneOutput(milestonesList);
});
});
});

现在无论我点击哪一行,每一行的点击事件都会被触发。我做错了什么?

我已经尝试了很多方法,没有 .each() 函数,它仍然会为表中的每一行触发。也许如果我展示其余的代码,它会有所帮助:

这是最后调用的 buildMilestoneOutput 函数:

function buildMilestoneOutput(container) {
container.innerHTML = "";
alert("Length: " + _milestones.length);
var s = "<table id='testscroll' style='width: 690px; padding: 10px;'><tr><td style='font-weight: bold;'>Title</td><td style='font-weight: bold;'>Description</td><td style='font-weight: bold;'>DueDate</td></tr>"
for (var i = 0; i < _milestones.length; i++) {
s += "<tr><td style='width: 300px; padding-bottom: 10px;'>" + _milestones[i].Title + "</td><td style='width: 350px; padding-bottom: 10px;'>" + _milestones[i].Description + "</td><td style='width: 30px; padding-bottom: 10px;'>" + _milestones[i].Name + "</td><td><span idx='" + i + "' style='margin-left: 5px; cursor: pointer;' id='tempmilestone'>remove</span></td></tr>";
}
s += "</table>";
container.innerHTML = s;
}

当用户单击“添加里程碑”按钮时调用此原始代码:

$("#lbAddMilestone").click(function () {

milestonesList.innerHTML = "";
var newMilestone = new GoalMilestone();
newMilestone.Title = "New Milestone";
_milestones.push(newMilestone);
buildMilestoneOutput(milestonesList);
wireupMilestoneDeletes();

return false;
});

这里是 wireupMilestoneDeletes:

function wireupMilestoneDeletes() {


$("#milestonesList").on('click', 'span[id*="tempmilestone"]', function (e) {
alert("ON: " + $(this).attr("idx"));
_milestones = _milestones.slice(parseInt($(this).attr("idx"), 10));
buildMilestoneOutput(milestonesList);
});
}

最佳答案

您不需要每个循环,更不用说两个了。您将点击事件绑定(bind)到任何一个 <span>id 的包含 "tempmilestone"并运行点击特定的处理程序 <span>那被点击了。因此,这应该足够了:

$("#milestonesList").on('click', 'span[id*="tempmilestone"]', function (e) {
alert("ON: " + $(this).attr("idx"));
_milestones = _milestones.slice(parseInt($(this).attr("idx"), 10));
buildMilestoneOutput(milestonesList);
});

关于javascript - 使用 JQuery .on() 函数为列表中的每个项目添加点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13012763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com