【问题标题】:Adding an integer to string将整数添加到字符串
【发布时间】:2023-03-30 16:24:01
【问题描述】:

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

【问题讨论】:

  • 您必须从字符串中提取变量,并将值连接到字符串。 JS 不会读取字符串中的变量值。或者更确切地说使用template literals。

标签: javascript html integer


【解决方案1】:

在使用js渲染动态元素时,有几个概念是你必须要知道的。

  1. 您的.close 按钮有一个click 侦听器。此侦听器永远不会触发,因为此侦听器仅与您的初始 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。 这是一个codeped 链接供您自己测试我所做的。

希望这对您有所帮助,任何其他问题都会很好:)

【讨论】:

  • 感谢您的回答,我认为与您的类似,但我的错误:),无论如何。可悲的是,我必须发出一个帖子请求,这就是练习的内容,即获取、发布、更新、删除。
  • @agrotis2231 我用相同的链接更改了 Codepen 中的代码。如果这个答案让你满意,请投票:)
  • GOAT,过去 3 个小时我一直在努力做到这一点。真的很欣赏。我试图投票,但它说它不会改变状态,因为我的帐户是新的。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
相关资源
最近更新 更多