Chrome 与火狐浏览器中的点击事件给出了不同的目标



TL;DR

单击此按钮会在点击事件中给出不同的目标,如果你在 Firefox 与 Chrome 中。似乎应该有一个优雅的解决方案来解决这个问题,而不必检查元素的父元素以查看它是否是一个按钮。

类似问题:

  • event.target.parentNode...指向Chrome和Firefox中的不同父母?<-如果我能帮助它,我不想使用jQuery。

.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>

您不需要引用e.target 。在 DOM 事件处理程序中,this 是指触发事件的元素。如果在按钮(父元素(上设置事件处理程序,则子元素不能是事件的触发器。

此外,您的代码尝试获取元素的id,但您的任何元素都没有为其建立id。您已经使用了 data-id ,如果需要,可以通过 element.dataset.attributeName 语法访问它。

//Get the div with this GUID.
const guid = '05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9';
const b = document.querySelector("[data-id='" + guid + "']");
// Add listener to delete the button when clicked.
b.addEventListener("click", delete_devices);
function delete_devices(e){
    this.remove();
}
<button data-id="05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9" 
        class="btn-floating btn-small waves-effect waves-light red delete-device ">
   <i class="material-icons" id="05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9">delete</i>
</button>

最新更新