javascript getElementById on span



我有一行结果:名称,金额,我想在行末尾添加一个X,允许删除整个行。

为了简洁,我在这里只给出了一行。有很多,我想把它放在一个for。 这是我的html:

let lignesRecurrentes = document.getElementsByClassName('ligne_recurrente')
for (var i = 0; i < lignesRecurrentes.length; i++) {
let ligneRecurrente = lignesRecurrentes[i]
let id = ligneRecurrente.id.replace('ligne_','')
let croix = document.getElementById('suppr_recurrente_'+id)
croix.addEventListener('click', function(){
console.log(croix.innerHTML)
}
)}
<div class="ligne_recurrente" id="ligne_3">
<span class="intitule" id="intitulerec_3">Cousteau</span>
<span class="montant">
<span class="chiffre_recur" id="montant_3">396,00</span>
<span class="euro">&#8364;</span>
<span id="suppr_recurrente_3 " >&nbsp;X</span>
</span>
</div>
<div id="smalrec_3"></div>

为什么croix是空的?不能在null上添加eventlistener ?

这是由于id="suppr_recurrente_3 "

中的尾随空格造成的。顺便说一句,你可以通过将行包装成一些div

来简化你的js。
<div class="rows">
<div class="ligne_recurrente" id="ligne_3">
<span class="intitule" id="intitulerec_3">Cousteau</span>
<span class="montant">
<span class="chiffre_recur" id="montant_3">396,00</span>
<span class="euro">&#8364;</span>
<span class="btn-remove">&nbsp;X</span>
</span>
</div>
<div id="smalrec_3"></div>
</div>

附加监听器执行此容器并检查所单击的元素是否有所需的类:

document.querySelector('.rows').addEventListener('click', function(e) {
var target = e.target, id;
if (target.classList.contains('btn-remove')) {
id = target.parentElement.parentElement.id.replace('ligne_', '');
console.log('line ' + id + ' should be removed');
}
});

您可以简单地将您的代码:

  • document.querySelectorAll ()
  • :胎
  • .forEach ()

为了删除整个行,在事件处理程序中使用.remove()就足够了。

代码片段:

document.querySelectorAll('.ligne_recurrente span span:last-child').forEach(function(ele) {
ele.addEventListener('click', function(e){
this.closest('div.ligne_recurrente').remove();
});
})
<div class="ligne_recurrente" id="ligne_3">
<span class="intitule" id="intitulerec_3">Cousteau</span>
<span class="montant">
<span class="chiffre_recur" id="montant_3">396,00</span>
<span class="euro">&#8364;</span>
<span id="suppr_recurrente_3" >&nbsp;X</span>
</span>
</div>
<div id="smalrec_3"></div>

最新更新