将整数添加到字符串

我正在尝试向卡 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;

  });


慕姐8265434
浏览 62回答 1
1回答

冉冉说

用js渲染动态元素时,有几个概念是必须要了解的。你的按钮有一个click监听器.close。该侦听器永远不会触发,因为该侦听器仅与您的初始 DOM 相关。但是您的关闭按钮是动态呈现的,这意味着侦听器与您的按钮无关。通过附加onclick到按钮并创建一个函数可以轻松解决这个问题。(示例如下)我检查了你的代码,你不必使用 id 机制来删除/隐藏你的card元素(除非你需要触发POST请求),你可以使用parentNode(示例如下)我对您的代码做了一些简单的更改:$(".create").click(function(){&nbsp; let element = `&nbsp; &nbsp; &nbsp; <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&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;bulk of the'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 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>`;&nbsp; document.getElementById("lastRow").innerHTML+=element;});function deleteCard(delBtn){&nbsp; delBtn.parentNode.parentNode.hidden = true}请注意我添加的函数和启用隐藏操作的 onclick。这是一个编码链接,供您自行测试我所做的事情。希望这对您有所帮助,任何其他问题都会很好:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript