gpt4 book ai didi

javascript - Chrome 与 Firefox 中的点击事件给出了不同的目标?

转载 作者:行者123 更新时间:2023-11-28 03:45:00 25 4
gpt4 key购买 nike

TL;DR:

如果您使用的是 Firefox 和 Chrome,则单击此按钮会在单击事件上提供不同的目标。似乎应该有一个优雅的解决方案来解决这个问题,而不必检查元素的父元素来查看它是否是按钮。

类似问题:

详细信息

JS:

    let guid = '05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9';
//Get the div with this GUID.
let elem = document.getElementById(guid);

//Get the button that belongs to this div that has the 'delete-device' class.
let b = elem.getElementsByClassName("delete-device")[0];

//Add listener to delete the div when clicked.
b.addEventListener("click", delete_devices, false);

HTML:

<button data-id="05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9" class="btn-floating btn-small waves-effect waves-light red delete-device ">
<i class="material-icons">delete</i>
</button>

在 Firefox 中,e.target 是按钮。

在 Chrome 中,e.target 是 <i>元素。

因此,当我们执行回调(如下)时,Chrome 找不到我们需要的 div,并将变量设置为 null,这(当然)会引发错误。

function delete_devices(e){
e.preventDefault();
let id = e.target.getAttribute('data-id');
let elem = document.getElementById(id);
elem.remove();
return true;
}

最佳答案

使用this引用单击的元素,如果您使用按钮,请确保确实在按钮及其中的某些元素上添加事件。

const guid = '05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9';
//Get the div with this GUID.
const elem = document.getElementById(guid);
const button = elem.querySelector("button.delete-device");
//Add listener to delete the div when clicked.
button.addEventListener("click", delete_devices, false);

function delete_devices(e){
let id = this.getAttribute('data-id');
console.log("Deleting widget: ", id)
const elem = document.getElementById(id);
elem.remove();
return true;
}
<div id="05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9">Device widget
<button data-id="05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9" type="button" class="btn-floating btn-small waves-effect waves-light red delete-device ">
<i class="material-icons">delete</i>
</button>
</div>

请注意,我删除了 event.preventDefault 。我想您使用它是因为您想阻止提交表单。任何<button>默认情况下是提交,要将其转换为普通按钮,请执行以下操作:

<button type="button">This does not submit form</button>

关于javascript - Chrome 与 Firefox 中的点击事件给出了不同的目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48572264/

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