文档写入原因设计缺陷

时间:2014-07-18 08:57:06

标签: javascript jquery document.write

我写了一个滑块功能。并根据滑块功能的值我在我的文档中打印一些消息。当我在更改滑块的值之后在滑块内使用DW时,无需样式打印消息。我该如何解决?

     $(function() {
        $( "#slider-5" ).slider({
           range:true,
           min: parseInt(ctime[0]),
           max: parseInt(ctime[ctime.length-1]),
           values: [ parseInt(ctime[4]),parseInt(ctime[len])],

           change: function( event, ui ) {
              $( "#slidevalue" )
                 .val( "$" + formatDateTime(ui.values[ 0 ]) + " - $" + formatDateTime(ui.values[ 1 ]) );
                 new_var=ui.values[0];
    document.write('<section id="cd-timeline" class="cd-container">')
    var ctime  = <?php echo json_encode($tweettimes); ?>;


    for(var x=0; x<10; x++){
    var datum = new Date(parseInt(ctime[x]));
    document.write('<div class="cd-timeline-block">')
    document.write('<div class="cd-timeline-img cd-location">')
    document.write('<img src="img/cd-icon-location.svg" alt="Location">')
    document.write('</div>')
    document.write('<div class="cd-timeline-content">')
    document.write('<h2>'+(x+1)+'</h2>')
    document.write('<p>'+<?php echo json_encode($content); ?>[x]+'</p>')

    document.write('<span class="cd-date">'+formatDateTime(datum)+'</span>')
    document.write('</div>')
    document.write('</div>')}
    document.write('</section>')
           }
       });
     });

1 个答案:

答案 0 :(得分:1)

请不要使用document.write。请改用document.createElement()

var body = document.getElementsByTagName('body')[0];

var section = document.createElement('section');
section.id = 'cd-timeline';
section.className = 'cd-container';
body.appendChild(section);

for (var x = 0; x < 10; x++) {
    var datum = new Date(parseInt(ctime[x]));

    var outerDiv = document.createElement('div');
    outerDiv.className = 'cd-timeline-block';
    section.appendChild(outerDiv);

    var div = document.createElement('div');
    div.className = 'cd-timeline-img cd-location';
    outerDiv.appendChild(div);

    var img = document.createElement('img');
    img.src = 'img/cd-icon-location.svg';
    img.setAttribute('alt', 'Location');
    div.appendChild(img);

    var div = document.createElement('div');
    div.className = 'cd-timeline-content';
    outerDiv.appendChild(div);

    var h2 = document.createElement('h2');
    div.appendChild(h2);
    h2_text = document.createTextNode('foo');
    h2.appendChild(h2_text);

    var p = document.createElement('p');
    div.appendChild(p);
    p_text = document.createTextNode('bar');
    p.appendChild(p_text);

    var span = document.createElement('span');
    span.className = 'cd-date';
    div.appendChild(span);
    span_text = document.createTextNode('foobar');
    span.appendChild(span_text);
}

DEMO