簡體   English   中英

HTML/CSS/Javascript 刪除按鈕

[英]HTML/CSS/Javascript delete button

我在 div 中有一個由兩個數組的內容確定的項目列表。

product_codes=[code1, code2, code3];
quantities=[1, 34, 67,];

每次將新代碼和數量添加到其各自的數組中時,我都有一個執行此操作的 javascript 函數:

    document.getElementById('cart_body').innerHTML='';
    cart_text='';
    elf='<br class="none"/>';
    for(i=0; i<product_codes.length; i++){
        cart_text+=(product_codes[i]+"  (x"+quantities[i]+")"+elf);
    }
    document.getElementById('cart_body').innerHTML=cart_text;

並根據此 HTML 執行操作:

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

使用這個 CSS:

.none{margin-top: 0px;}

(CSS 簡單地覆蓋了我給 ALL 的另一種樣式
標簽)

我想要做的是在添加到 cart_text 的每一行的末尾(在插入的換行符之前),是在中心添加一個帶有 x 的小圓形按鈕(我想在 Bootstrap 中有類似的東西,但我我無法使用它或任何其他庫),當單擊時,從 div 中僅在該行上刪除它旁邊的文本(產品代碼和數量),並從各自的數組中刪除兩個項目(產品代碼和數量) . 理想情況下,上述刪除按鈕看起來類似於可讓您刪除已發布評論的按鈕(在 Stack Overflow 上)。

請只回答 Vanilla CSS 和 Javascript。 請不要圖書館。

如果不是問太多,工作的 JsFiddle 也會很棒。

謝謝!

編輯

嘗試按下按鈕:#1

#close_button{
 border:  1px solid black;
 padding-top: 0;
 max-width: 15px;
 max-height:  15px;
 background-color: lightBlue;
 border-radius: 90px;
 font-size: 14px;
 text-align:  center;
}

<div id='close_button'>x</div>

這不起作用,因為我無法獲得正確的大小,而 x 位於圓的確切中心。 我嘗試填充,所有這些好東西,但無濟於事。

您可以在https://jsfiddle.net/osha90/krrhvdmj/使用以下代碼

<div id='cart_body'>
<p>
  code1 x1 <span style="display:inline-block;width:30;height:30;background-color:#d2d2d2; border-radius: 50%;font-size:12px;line-height:18px;">X</span> 
</p>

  var product_codes=["code1", "code2", "code3"];
 var quantities=[1, 34, 67,];

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

for(i=0; i<product_codes.length; i++){
    var p = document.createElement("p");
  p.appendChild(document.createTextNode(product_codes[i] +"     X    "+quantities[i]));
    var span = document.createElement("span");
    span.appendChild(document.createTextNode("X"));
    span.classList.add("delete");
    var a = document.createAttribute("data-productCode");
      a.value = product_codes[i];
    span.setAttributeNode(a);
    p.appendChild(span);
     span.addEventListener("click",removeElm);
  document.getElementById('cart_body').appendChild(p);
     }

function removeElm(){
    var div = this.parentNode.parentNode;
    for(i=0; i<product_codes.length; i++){
        if(product_codes[i] == this.getAttribute("data-productCode"))
        {product_codes.splice(i,1);
           quantities.splice(i,1);
        console.log(product_codes);
         console.log(quantities);
            break;
        }
    }
    div.removeChild(this.parentNode);

}

css代碼

.delete{
  display: inline-block;
     width: 19px;
    height: 18px;
    text-align: center;
  background-color: #D2D2D2;
    border-radius: 50%;
  font-size: 12px;
  line-height: 18px;
  cursor: pointer;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM