gpt4 book ai didi

javascript - 使用 "this"作为html类的点击事件

转载 作者:行者123 更新时间:2023-11-28 15:04:07 24 4
gpt4 key购买 nike

我希望在一行代码中为具有特定类名的所有 html 标签设置一个单击事件。显然它无法识别this作为引用自身的 html 对象或容器,并且 myFunction 永远不会在任何单击时执行。我正在尝试使用 this因为我想在被点击的标签内部搜索其他 html 元素,并且我希望标签不必为每个标签都具有唯一的 id 和点击事件,因为这样的标签有很多。

$(document).ready(){
$(".myClass").click(function () {
toggleDriver(this);
});
};

function toggleDriver(driver) {
zoomed = false;
$("#zoomer").css("display", "none");
map.fitBounds(bounds);
var dContainers = $("orders").find(".driverSection"); // first find all driver sections and loop through each
for (var x = 0; x < dContainers.length; x++) {
var tContainer = $(dContainers[x] + " .transactions"); // find transaction section for this driver section
if (dContainers[x].attr('id') == $(driver).attr('id')) { // is this the driver section that was clicked?
if ($(tContainer).css("display") == "none"){ // if collapsed
$(tContainer).slideDown("fast"); // expand it
exp = $(driver).attr("id"); // save which driver is expanded in global var
setDeliveryMarkers(); // set the map with driver marker and his delivery markers
}
else {
$(tContainer).slideUp("fast"); // it was expanded so collapse it
exp = ""; // save the fact that no driver transactions are expanded
if (trans != "") { //any transaction for this driver that had focus (white border) needs to lose it
$("#" + trans).css("border-color", "transparent");
// we need to stop the marker animation for this transaction that no longer has focus
for (var x = 0; x < deliveryMarkers.length; x++) {
if (deliveryMarkers[x].getTitle() == trans) {
deliveryMarkers[x].setAnimation(null);
break;
}
}
}
trans = ""; // clear this value to show that no transactions are in focus
setDriverMarkers(); // since no transaction section is expanded, show all drivers markers instead
}
}
else {
$(tContainer).css("display", "none"); // transaction container is not inside clicked driver section so close it
}
}
}

有人知道更好的方法来实现我想要的吗?看来我只遗漏了一个小细节。谢谢。

帖子编辑:这些具有此类名称的 html 标签在 document.ready 之后加载,因此也许有人可以提供针对该潜在问题的答案。谢谢。

最佳答案

由于元素是动态加载的,因此您需要使用 Event Delegation

它看起来像下面这样:

$(function () {
$(document).on("click", ".myClass", function () {
toggleDriver(this);
});
});

关于javascript - 使用 "this"作为html类的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39922891/

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