0

所以我这里有个问题。我为一些 div 设置了一些自定义样式,使它们暂时不可见。但是,当我使用文档写入功能从外部 .js 文件生成文本时,这些自定义样式似乎不会触发:

CSS:

<style type="text/css">
        .section 
        {
            display: none;
        }
        .section#form1
        {
            display: block;
        }

用于切换可见性的 JavaScript 函数:

function toggleVisibility(newSection) 
        {
            $(".section").not("#" + newSection).hide();
            $("#" + newSection).show();
        }

在生成此页面上大部分内容的递归循环函数中的某个地方我有这个

...
if (step != 1)
                    {
                        document.write("</div>");
                    }
                    document.write("<div id='form"+step+"' class='section'>");
...

我是否需要某种代码来分配 JavaScript 将表单的所有元素打印到某个外部 div 的位置?我似乎无法理解为什么所有的 div 一开始都是可见的,我之前做了同样的代码,然后它工作得很好。也许 document.write 的一个很好的替代品可能会奏效。感觉像 document.write sorta 覆盖一切。

$(document).ready(function()
    {       
        $('#show-results').click(function() 
        {
            $.post('JSAAN.php', function(data) 
            {
                var pushedData = jQuery.parseJSON(data);

                // Uses the function from loop.js
                document.write("<form id='evalForm' onsubmit='return false;'>");
                var fieldsetActive = 0;
                loop(pushedData);
            })
        })
    });

And the loop function (who's in a separate file starts like this:

function loop(obj) {
    // Starts the form
        $.each(obj, function(key, val) {
            if($.isPlainObject(val) || $.isArray(val)) { // object, call recursively
4

3 回答 3

3

Instead of using document.write to create your div, consider using document.createElement.

var elem = document.createElement('div'),
    formStep = 'form' + step;
elem.setAttribute('id', formStep);
elem.setAttribute('class', 'section');

This will insert the element into the DOM. document.write is not recommended for this type of usage.

If you need to use jQuery:

// using document.createElements('div') as the selector is the fastest way
var elem = $(document.createElement('div')),
    formStep = 'form' + step;
elem.attr('id', formStep).attr('class', 'section');

Let me know if you have any questions.

于 2012-07-17T14:04:04.887 回答
2

You shouldn't be using document.write. If the page is fully loaded, it will erase the entire page (including the CSS).

You seem to be using jQuery already, so use its .append or .html methods instead.

于 2012-07-17T14:11:54.640 回答
0

because when you use document.write it overwrites everything in the page including styles etc, I think you should consider using DOM functions instead of using document.write

于 2012-07-17T14:12:27.800 回答