鍍金池/ 問(wèn)答/HTML/ js 刪除元素報(bào)錯(cuò)

js 刪除元素報(bào)錯(cuò)

直接看代碼,msgList 是一個(gè) ul 元素,target.parentNode 是 ul 下的 li,target 是 li 內(nèi)部的 a 標(biāo)簽,要實(shí)現(xiàn)的功能是在 ul 上設(shè)置了 click 的事件監(jiān)聽,當(dāng)點(diǎn)擊 a 的時(shí)候,通過(guò)事件冒泡,會(huì)刪除包含該 a 標(biāo)簽的 li 標(biāo)簽。但是如下的寫法最終該元素也刪除了,但是控制臺(tái)卻報(bào)了一個(gè)錯(cuò)誤,沒(méi)想明白怎么回事,請(qǐng)大神指教一二。

圖片描述

報(bào)的錯(cuò)誤:

圖片描述

但是我不使用事件委托的方式,直接遍歷所有的 a 標(biāo)簽,就是正常的。

圖片描述

回答
編輯回答
入她眼

MDN上有針對(duì)removeChild上可能造成的異常有解釋:

The method throws an exception in 2 different ways:

  • If the child was in fact a child of element and so existing on the
    DOM, but was removed the method throws the following exception:

??Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

  • If the child doesn't exist on the DOM of the page, the method throws
    the following exception:

Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.

If child was in fact a child of element at the time of the call, but was removed by an event handler invoked in the course of trying to remove the element (eg, blur.)

2017年11月28日 12:56
編輯回答
茍活

第一張圖里面使用 事件委托的方式,剛才執(zhí)行了一遍,也沒(méi)報(bào)錯(cuò),
看代碼也沒(méi)任何問(wèn)題。應(yīng)該是其它地方出問(wèn)題了。

2017年3月10日 07:12