亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將整數添加到字符串

將整數添加到字符串

慕姐8265434 2023-09-28 09:36:13
我正在嘗試向卡 ID 添加一個整數,以便在按下刪除按鈕時可以將其刪除。有什么幫助嗎?     var variable = '' +   '<div id="card+$num.toString(cnt);" class="card col-3" style="width: 18rem;" style="margin-right=3%; margin-right=3%">' +   '            <img src="..." class="card-img-top" alt="..." id="image"+String(cnt)>' +   '            <div class="card-body">' +   '                <h5 class="card-title" id="title"+String(cnt) contentEditable="true"; >Card title</h5>' +   '                <p class="card-text" id="desc"+String(cnt) contentEditable="true">Some quick example text to build on the card title and make up the' +   '                    bulk of the' +   '                    card\'s content.</p>' +   '                <a href="#" class="btn btn-primary" id="button"+ String(cnt) >Go somewhere</a>' +   '                <a href="#" id="btn"+String(cnt) class="close"+String(cnt)>Delete</a>' +   '            </div>' +   '        </div>' +   '';  $(".create").click(function(){    document.getElementById("lastRow").innerHTML+=variable;  });  $(".close"+String(cnt)).click(function(){    console.log("Doulevw!");    document.getElementById("card"+String(cnt)).hidden=true;  });
查看完整描述

1 回答

?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

用js渲染動態元素時,有幾個概念是必須要了解的。

  1. 你的按鈕有一個click監聽器.close。該偵聽器永遠不會觸發,因為該偵聽器僅與您的初始 DOM 相關。但是您的關閉按鈕是動態呈現的,這意味著偵聽器與您的按鈕無關。通過附加onclick到按鈕并創建一個函數可以輕松解決這個問題。(示例如下)

  2. 我檢查了你的代碼,你不必使用 id 機制來刪除/隱藏你的card元素(除非你需要觸發POST請求),你可以使用parentNode(示例如下)

我對您的代碼做了一些簡單的更改:

$(".create").click(function(){

  let element = `

      <div id="card" class="card col- 3" style="width:18rem;style="margin-right=3%; margin-right=3%"><img src="..." class="card-img-top" alt="..." id="image"+String(cnt)><div class="card-body"><h5 class="card-title" id="title" contentEditable="true">Card title</h5><p class="card-text" id="desc" contentEditable="true">Some quick example text to build on the card title and make up the                     bulk of the'                    card\'s content.</p><a href="#" class="btn btn-primary" id="button"+ String(cnt) >Go somewhere</a><a href="#" class="close" onclick='deleteCard(this)'>Delete</a></div></div>`;

  document.getElementById("lastRow").innerHTML+=element;

});


function deleteCard(delBtn){

  delBtn.parentNode.parentNode.hidden = true

}


請注意我添加的函數和啟用隱藏操作的 onclick。這是一個編碼鏈接,供您自行測試我所做的事情。


希望這對您有所幫助,任何其他問題都會很好:)


查看完整回答
反對 回復 2023-09-28
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號