gpt4 book ai didi

javascript - 使用 javascript 函数替换 div 的内容,注意到奇怪

转载 作者:行者123 更新时间:2023-11-30 06:30:37 25 4
gpt4 key购买 nike

我正在尝试运行使用函数生成内容的代码,并让内容可以在点击时更改,但是当内容更改时,没有再次应用任何 CSS。这真的很奇怪。

这是我的代码示例,一般化:

function flush(divId) {
$(divId).parentNode.removeChild(divId);
}

function makeContent(arg1,arg2,arg3) {
document.write('<div class="exampleClass" id="' + arg1 + 'Id">');
if(arg3 < 1000) { // Chose an arbitrary number
if (arg2 != "ArbritraryArg") {
document.write('<span class="spanLink" onclick="flush(\'' + arg1 + 'Id\')\; makeContent(\'' + arg1 + '\',\'Something\',' + arg3 + ')\;">Blarg</span>');
} else {
document.write('<span class="spanLink" onclick="flush(\'' + arg1 + 'Id\')\; makeContent(\'' + arg1 + '\',\'SomethingElse\',' + arg3 + ')\;">Yearg</span>');
}
}

var i = 0;
var mdArray = eval(arg1 + 'Id' + arg3); // This is a multidimensional array which does exist just above the lines for function flush(). There are no possible problems in the array's definition, and so I did not include it here.
do {
document.write('<div class="exampleClass2">' + mdArray[i][0] + '</div><div class="exampleClass3">' + mdArray[i][1] + '</div>');
i++;
} while (i < mdArray.length);

document.write('</div>');
var parentDiv = document.getElementById('parentDiv');
parentDiv.insertBefore(monster + 'Set',parentDiv.firstChild);
}

document.write('<div id="parentDiv">');
makeContent('Arg1','Something',Arg3);
document.write('</div>');

我的问题是,当我通过在 .html 文档中引用此脚本文件进行测试时,第一次执行 makeContent() 时(当由脚本本身执行时),一切都很完美......但除此之外,并非如此。我已经使用外部 <span> 测试了 flush() 函数调用 flush 函数的链接,它工作正常,只是删除 makeContent() 数据,并将 HTML 文档中的其他所有内容留在那里。

所以如果我点击 <span>在我编写的示例代码的第 9 行生成的链接,内容发生了变化,但没有重新应用相关的 CSS,HTML 文档中的所有其他内容也消失了。这是怎么回事?如果我按照与测试 flush() 的方式相同的方式使用外部链接尝试相同的功能,则会发生同样的问题。

这是我得到 HTML 页面的方式,以防万一有人想知道:

<html><head><title>Testing</title>
<link rel="stylesheet" href="stylesheet.css">
</head><body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,...</p>
<script href="script.js"></script>
<p><span class="spanLink" onclick="flush('Arg1Id');">Get rid of the content (TEST)</span></p>
<p><span class="spanLink" onclick="flush('Arg1Id'); makeContent('Arg1','Arg2',Arg3);">Try regenerating the content (TEST)</span></p>
</body></html>

感谢所有帮助!

编辑:所以我刚刚注意到在 test.html 文件上,当我尝试重新生成内容时,标题从“Testing”变为“test.html”......是新生成的内容会杀死文件中的所有 HTML 元素吗?

最佳答案

document.write 只应在页面加载时使用,如果您在页面加载后触发该事件,它将覆盖您的内容并且您的页面将包含该内容。而是尝试将文本插入到 DOM 中。使用 innerHTML

关于javascript - 使用 javascript 函数替换 div 的内容,注意到奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17885049/

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