gpt4 book ai didi

javascript - 是否可以输出 Javascript 中元素之外的内容?

转载 作者:行者123 更新时间:2023-11-27 22:36:59 25 4
gpt4 key购买 nike

我不确定这是否是一个愚蠢的问题(我感觉到有人反对),但我在网上搜索并没有找到任何有用的信息。

如果我想在页面上显示一些内容,我可以使用:

document.getElementById("id").value="whatever";

是否可以摆脱此处包含元素的概念,以便我可以执行以下操作:

<html>
<body>
<script>write something here with javascript, no need for element?</script>
</body>
</html>

我知道这可以通过使用类似的东西来实现:

function e(){
return "whatever";
}

但我正在尝试使用 this QRCode 生成器需要 ID。但是,我使用 JSPc:forEach 循环中动态生成几行 QR 码,但我不知道如何为每次迭代显示 QR 码循环的。

JSP 上下文:

<c:forEach items="item" var="${items">

<!-- display QR code here with value from ${item.qr} -->

</c:forEach>

这就是当我使用类似以下内容时发生的情况:

<c:forEach items="item" var="${items}">

<script>
new QRCode(document.getElementById("qrcode"), "${item.qr}");
</script>

<div id="qrcode"></div>

</c:forEach>

结果:

enter image description here

通过执行以下操作修复:

<c:forEach items="item" var="${items">

<script>
var div = document.createElement("div");
div.id = "${item.id}";
new QRCode(document.getElementById("${item.id}"), "${item.qr}");
</script>

</c:forEach>

最佳答案

您可以创建一个元素及其文本,如下所示:

var div = document.createElement("div");
div.id = "yourID";
var divText = document.createTextNode("Whatever");
div.appendChild(divText);
document.body.appendChild(div);

所以就你的 html 代码而言,它将是

<html>
<body>
<script>
var div = document.createElement("div");
div.id = "yourID";
var divText = document.createTextNode("Whatever");
div.appendChild(divText);
document.body.appendChild(div);
div.addEventListener("click", function(el) {
alert("clicked the created element with id: " + el.target.id);
}, false);
</script>
</body>
</html>

关于javascript - 是否可以输出 Javascript 中元素之外的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39016663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com