2

我正在尝试运行使用函数生成内容的代码,并在点击时更改内容,但是当内容更改时,不会再次应用任何 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() (当由脚本本身执行时),一切都很完美......但除此之外,并非如此。我已经使用只调用 flush 函数的外部<span>链接测试了 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元素?

4

1 回答 1

0

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

于 2013-07-26T16:17:27.487 回答