【问题标题】:How do I add a value from a callback into a new element with setAttribute?如何使用 setAttribute 将回调中的值添加到新元素中?
【发布时间】:2019-09-23 09:04:38
【问题描述】:

我需要将回调的值添加到我的 setAttribute 中。我怎么做?

这个值是稍后从表中取出数据所必需的。

这是代码:

row.forEach(function(row) {
         var subchapname = document.createElement("div");
         subchapname.setAttribute("id", "subchaptertitle");
         subchapname.setAttribute("subid", '"+row+"');
         subchapname.setAttribute("onclick","{ alert('You are not going to believe this!') } ");
         subchapname.textContent = row.subname;
         rows.appendChild(subchapname);

基本上,这意味着: 回调 = 行

这个回调需要添加到subchapname.setAttribute("subid", '"+row+"');

这可能吗?

这是实际结果:

<div id="subchaptertitle" subid="&quot;+row+&quot;" onclick="{ alert('You are not going to believe this!') } ">bos in brand</div>```

【问题讨论】:

  • 您希望“subid”属性最终包含什么值?行回调实际上并没有返回值,它只是设置了一堆属性,然后在 div 中附加一些文本。
  • 感谢您的回复 :) 我实际上需要该行中的 id(我称之为 subid)。该行以这种方式来自 sqlite 数据库:db.all("SELECT subname FROM chaptree WHERE (chapname='" + chapname + "') ORDER BY suborder", function(err,row)
  • 你应该可以做到subchapname.setAttribute("subid", row)subchapname.setAttribute("subid", row.someProperty)row有什么样的数据结构?您可以控制台记录并更新问题吗?

标签: javascript node.js sqlite electron setattribute


【解决方案1】:

subid 不是在其中存储数据的属性,因此您不能将这样的属性添加到 html-tag 并用值填充它(当然,将字符串写入其中会起作用,但这就是您需要?)。但是如果你使用 html5,你可以添加数据集。因此,使用此解决方案将您的行值存储在 subid 的数据集属性中。 如果 row 是一个对象,并且您想查看 Object 的字符串化值,请在将其存储到数据集中之前使用 JSON.stringify

row.forEach(function(row) {
  var subchapname = document.createElement("div");
  subchapname.setAttribute("id", "subchaptertitle");
  subchapname.dataset.subid = row;
  // subchapname.dataset.subid = JSON.stringify(row);
  subchapname.setAttribute("onclick","{ alert('You are not going to believe this!') } ");
  subchapname.textContent = row.subname;
  rows.appendChild(subchapname);
});

您的元素现在应该如下所示:

<div id="subchaptertitle" onclick="{ alert('You are not going to believe this!') } " data-subid="[object Object]"></div>

或者如果你使用了 JSON.stringify:

<div id="subchaptertitle" onclick="{ alert('You are not going to believe this!') } " data-subid="what ever row is as a string"></div>

要将值记录到控制台,(在将标签添加到 DOM 之后)执行以下操作:

console.log(document.getElementById('subchaptertitle').dataset.subid);

如果您使用 JSON.stringify,现在使用类似这样的内容:

console.log(JSON.parse(document.getElementById('subchaptertitle').dataset.subid));

【讨论】:

  • 感谢您绝对出色的帮助!我仍在学习用 JavaScript 编程,但我不知道数据集属性。您的解决方案和解释对我帮助很大!我现在可以使用数据集中的值进行其他调用。再次感谢您的帮助!!
猜你喜欢
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多