如何确定单击了具有相同 class 的序列中的哪个 div

How to Identify which div in a sequence with the same class was clicked

我有两个数组:

codes=[code1, code2, code3];
quantities=[23, 67, 87];

还有这个HTML

<div id='cart_body'></div>

和这个脚本

Delete=function(){

}

document.getElementById('cart_body').innerHTML='';
    cart_text='';
    emp='<div class="close_button" onClick='Delete()'>x</div>';
    open_span='<span class="close_span ">';
    close_span='</span>';
    elf='<br class="none"/>';
    for(i=0; i<product_codes.length; i++){
//the two lines directly below this line are actually one continuous line
        cart_text+=(open_span+codes[i]+"  
        (x"+quantities[i]+")"+close_span+emp+elf);
    }


    document.getElementById('cart_body').innerHTML=cart_text;

和这个 css:

.close_button{
display: inline-block;
background-color: grey;
height: 12px;
width: 12px;
border-radius: 6px;
}
span{

display: inline-block;
}

此脚本的目的是编写文本行。每行有一个代码,一个数量,还有一个div。 div 也有一些样式可以变成圆形按钮,但那一点是无关紧要的。

我的问题是:我可以写什么,以便删除函数可以检测 class "close_button" 中的哪个 div 触发了该函数?

基于此,该函数需要删除该行文本(包含被单击的 div、代码和数量的行),以及删除这两项(代码和数量)来自各自的数组。

我该怎么做?

如果我说得不够清楚,请随时提问:)

P.S。 (特别感谢 fiddle 的回答);-)

P.P.S。请仅定期 JavaScript。请不要使用库或框架。

Fiddle Here

点击显示“点击我”的按钮。在实际代码中,我不知道数组中会有多少项,但每个项的数量是相同的。就像我说的,我需要任何一个小圆形按钮,在单击时删除它自己和同一行上的所有文本,以及该行上的文本所代表的数组中的项目。

该函数最好命名为 deleteDiv 或更通用地命名为 deleteElement 并且可用于删除任何元素。

您可以使用 this:

传递对调用侦听器的元素的引用
emp = '<div class="close_button" onClick="deleteElement(this)">x</div>';

那么函数可以是:

function deleteElement(el) {
  el.parentNode.removeChild(el);
} 

我可以写什么,以便删除函数可以检测到 class "close_button" 中的哪个 div 触发了该函数?

为此,我首先建议将每个元素放在一个 <div> 中,而不是一个 <span> 和一个单独的 <div>。然后我们可以删除父级:

cart_text+= "<div>"+(open_span+codes[i]+"   (x"+quantities[i]+")"+close_span+emp+elf)+"</div>";

要删除父项,您可以执行 item.parentNode.remove();,您可以在 onclick 事件中将元素作为 this 传递:

<div class="close_button" onclick="deleteItem(this)">x</div>

以及删除元素的函数:

deleteItem = function(item) {
    item.parentNode.remove();
}

Here is a fiddle example.

数组中的项呢?

为此,我们需要从元素中获取文本,删除具有 (x[Number]) 的文本,然后删除 trim 的文本。从那里我们需要遍历数组并找到具有匹配文本的元素并将该元素从我们的数组中删除。为此,我创建了一个单独的函数来从数组中删除一个元素:

function removeTextFromArray(array, text){
    for (var i=array.length-1; i>=0; i--) {
        if (array[i] === text) {
            array.splice(i, 1);
            quantities.splice(i, 1); // Removes from quantities at same position
            return array;
        }
    }
}

并获取文本,并删除我们不需要的内容:

deleteItem = function(item) {
    item.parentElement.remove();
    // Gets the text in the close_span class of the parent div  
    var textInNode = item.parentNode.getElementsByClassName("close_span")[0].innerHTML;
    // Removes the items in (...) and trims the string.
    textInNode = textInNode.replace(/ *\([^)]*\) */g, "").trim();
    // Takes the string and removes it from the codes array
    codes = removeTextFromArray(codes, textInNode);  
}

Here is a Fiddle Example of that.

这里一切正常。只需单击 运行

product_codes=['code1', 'code2', 'code3'];
quantities=[23, 67, 87];

function deleteIt(e){
  e.parentNode.remove();
}

document.getElementById('cart_body').innerHTML='';
cart_text='';
emp='<div class="close_button" onclick="deleteIt(this)">x</div>';
open_span='<span class="close_span ">';
close_span='</span>';
elf='<br class="none"/>';
for(i=0; i<product_codes.length; i++){
    cart_text+='<div>'+(open_span+product_codes[i]+"(x"+quantities[i]+")"+close_span+emp+elf)+'</div>';
}

document.getElementById('cart_body').innerHTML=cart_text;
.close_button{
display: inline-block;
margin:4px;
  position:relative;
background-color: red;
color:blue;
border:1px solid transparent;
border-radius: 50%;
padding:2px 7px;

cursor:default;  
 
}
.close_button:hover{
border: 1px solid blue;
}
span{

display: inline-block;
}
<div id='cart_body'></div>

x = document.getElementsByClassName("e");

for (var i=0; i < x.length; i++) {
  x[i].onclick = function() {deleteIt(this)}
  
}

function deleteIt(x) {

    x.style.display = "none"
    
  }
<div class=e>Some text 0</div>
<div class=e>Some text 1</div>
<div class=e>Some text 2</div>
<div class=e>Some text 3</div>
<div class=e>Some text 4</div>
<div class=e>Some text 5</div>

为纯 JS 编辑,多亏了这个 post Applying onClick to Element Array in a For Loop

如您所愿,下面是不使用任何框架或库的解决方案。

HTML:

<div id='cart_body'></div>
<button OnClick='myfunction()'>Click me</button>

JS:

    codes=['hi', 'random text', 'lorem ipsum'];
quantities=[1, 45, 32];
 deleteDiv = function(e) {
    console.log(e);

     var code_name_str = e.currentTarget.parentNode.getElementsByTagName('span')[0].innerText.split('(')[0];

     var code_name = code_name_str.substring(0, code_name_str.length - 1);
     var code_index = codes.indexOf(code_name);
     if (code_index > -1) {
        codes.splice(code_index, 1);
     }
         console.log(codes);
         var code_quantity_str = e.currentTarget.parentNode.getElementsByTagName('span')[0].innerText.split('(')[1];

     var code_quantity = code_quantity_str.substring(0, code_quantity_str.length - 1);
     var quantity_index = quantities.indexOf(parseInt(code_quantity));
     if (quantity_index > -1) {
        quantities.splice(quantity_index, 1);
     }
      console.log(quantities);
    e.currentTarget.parentNode.parentElement.removeChild(e.currentTarget.parentNode);
}
myfunction = function(){
document.getElementById('cart_body').innerHTML='';
    open_div = '<div>'
        cart_text='';
        emp='<div id="sam" class="close_button"  onclick="deleteDiv(event)">x</div>';
        open_span='<span class="close_span">';
        close_span='</span>';
        elf='<br class="none"/>';
    close_div = '</div>'
        for(i=0; i<codes.length; i++){
            cart_text+=(open_div+open_span+codes[i]+"   ("+quantities[i]+")"+close_span+emp+elf+close_div);
        }
        document.getElementById('cart_body').innerHTML=cart_text;
}

CSS:

#cart_body{
    height: 300px;
    width: 300px;
    text-align: center;
    border: 1px solid black;
}
span{
    text-align: center;
    display: inline-block;
}
    .close_button{
    border:  1px solid black;
    width: 12px;
    height:  12px;
    border-radius: 90px;
    font-size: 12px;
    text-align:  center;
    line-height: 11px;
    background-color: lightGrey;
    display:  inline-block;
    margin-left:  20px;
    }
body{
    font-size: 12px;

}
.close_button:hover{
    color: red;
    border: 2px solid red;
    font-weight: bold;
    }

Fiddle Link:

https://jsfiddle.net/uhwLg8ss/4/