gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:27:53 25 4
gpt4 key购买 nike

我有两个数组:

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 也有一些样式可以变成圆形按钮,但那一点是无关紧要的。

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

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

我该怎么做?

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

附言(特别感谢能用 fiddle 回答);-)

附言请仅使用常规 JavaScript。请不要使用库或框架。

fiddle Here

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

最佳答案

我可以写什么以便删除函数可以检测类“close_button”中的哪个 div 触发了该函数?

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

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

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

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

关于javascript - 如何识别具有相同类的序列中的哪个 div 被单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31715767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com