简体   繁体   English

如何识别单击了具有相同类的序列中的哪个 div

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

I have two arrays:我有两个数组:

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

and this HTML和这个 HTML

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

and this script和这个脚本

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;

and this css:和这个CSS:

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

display: inline-block;
}

The purpose of this script is to write lines of text.此脚本的目的是编写文本行。 Each line has one code, and one quantity, as well as a div.每行有一个代码,一个数量,以及一个 div。 The div also has some styling that makes in into a circular button, but that bit is irrelevant. div 也有一些样式,可以做成圆形按钮,但这一点无关紧要。

My questions are these: What can I write so that the delete function can detect which div in the class "close_button" triggered the function?我的问题是这些:我可以写什么,以便删除函数可以检测到“close_button”类中的哪个 div 触发了该函数?

BASED ON THAT, the function needs to delete that line of text (the line that contains the div that was clicked, the code, and the quantity), as well as delete those two items (the code and quantity) from their respective arrays.基于此,该函数需要删除该行文本(包含被点击的 div、代码和数量的行),并从各自的数组中删除这两项(代码和数量)。

How can I do this?我怎样才能做到这一点?

If I'm not being clear enough feel free to ask :)如果我不够清楚,请随时提问:)

PS (answers with a working fiddle would be especially appreciated) ;-) PS(特别感谢有工作小提琴的答案);-)

PPS please regular JavaScript only. PPS 请仅使用常规 JavaScript。 No libraries or frameworks, please.请不要使用库或框架。

Fiddle Here在这里小提琴

Click the button that says click me.单击显示单击我的按钮。 In the actual code, I do not know how many items there will be in the arrays, but there will be an identical amount in each.在实际代码中,我不知道数组中有多少项,但每个项中的数量相同。 Like I said, I need any of the small circular buttons, when clicked, to delete itself and all text on the same line, as well as the items in the arrays that the text on that line represents.就像我说的,我需要任何一个小的圆形按钮,当点击时,删除它自己和同一行上的所有文本,以及该行上的文本所代表的数组中的项目。

The function would be better named as deleteDiv or more generically as deleteElement and can be use to delete any element.该函数最好命名为deleteDiv或更一般地命名为deleteElement ,可用于删除任何元素。

You can pass a reference to the element that called the listener using this :您可以传递给使用这款名为监听元素的引用:

emp = '<div class="close_button" onClick="deleteElement(this)">x</div>';

then the function can be:那么函数可以是:

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

What can I write so that the delete function can detect which div in the class "close_button" triggered the function?我可以写什么以便删除函数可以检测到“close_button”类中的哪个 div 触发了该函数?

To do this I would first recommend having each element in a <div> rather than a <span> and a separate <div> .为此,我首先建议将每个元素放在<div>而不是<span>和单独的<div> Then we could just remove the parent:然后我们可以删除父级:

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

To remove the parent you can do item.parentNode.remove();要删除父项,您可以执行item.parentNode.remove(); , where you can pass the element as this in the onclick event: ,您可以在onclick事件中将元素作为this传递:

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

And the function to remove the element:以及删除元素的函数:

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

Here is a fiddle example.这是一个小提琴示例。

What about the item in the array?数组中的项呢?

To do this we need to get the text from our element, remove the text that has (x[Number]) , then trim that.为此,我们需要从元素中获取文本,删除具有(x[Number])的文本,然后对其进行修剪。 From there we need to go through the array and find the element with the matching text and remove that element from our array.从那里我们需要遍历数组并找到具有匹配文本的元素,然后从我们的数组中删除该元素。 To do that I made a separate function for removing an element from an array:为此,我创建了一个单独的函数来从数组中删除元素:

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;
        }
    }
}

And to get the text, and remove the stuff we don't want in that text:并获取文本,并删除该文本中我们不想要的内容:

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.这是一个小提琴示例。

Here it is all working.这里一切正常。 Just click Run只需点击运行

 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>

Edited for pure JS, thanks to this post Applying onClick to Element Array in a For Loop为纯 JS 编辑,感谢这篇文章在 For 循环中将 onClick 应用到元素数组

As you want here is the following solution without using any frameowrk or library.如您所愿,这里是以下解决方案,不使用任何框架或库。

HTML: HTML:

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

JS: 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: 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/ https://jsfiddle.net/uhwLg8ss/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM