2014-03-02 36 views
-1

我想现在有没有像JavaScript的document.write()的任何功能,而不是替换元素它追加他们,因为我建立一个功能,用代码替换用户输入,它的工作但问题不在于在特定位置添加代码,而是替换所有页面内容。替换为document.write但附加功能

我的功能代码。

function one(json) { 
     var j = 0; 
     var img = new Array(); 
     var maxpost=json.feed.entry.length; 
     for (var i = 0; i < numposts1; i++) { 
      var entry = json.feed.entry[i]; 
      var posttitle = entry.title.$t; 
      var pcm; 
      var posturl; 
      var postAuthor = entry.author[0].name.$t; 
      var postLabels = entry.category[1].term; 

if ((i>0)&&(i<maxpost)) { 
var trtd = '<a href="'+posturl+'">'+posttitle+'</a><h2>'+posttitle+'</h2>  <span>'+postAuthor+'</span><span>'+postLabels+'</span><div>'+img[i]+'</div>'; 
document.write(trtd); 
} 
      j++; 
     } 
    } 

,这是代码

$(document).ready(function(){ 
    $('.widget-content').each(function(){ 
var b = $(this).html(); 
    var a = b.match(/[^[\]]+(?=])/g); 
var code = $('#myscript').attr('src'); 
    var script= document.createElement('script'); 
    script.type='text/javascript'; 
    script.src=code; 
$('.HTML').append("<script id='myscript' src='/feeds/posts/default/-/Break?published&amp;alt=json-in-script&amp;callback=one'><\/script>"); 

    }); 
}); 

Live demo for the problem

+0

在jQuery中大约有四十种这样的方法。 – adeneo

+0

@adeneo你可以给一些例子 – abdel

回答

0

在原始的JavaScript可以使用一个元件的innerHTML属性,例如,第二部分:

var stringToAppend = "<script id='myscript' src='/feeds/posts/default/-/Break?published&amp;alt=json-in-script&amp;callback=one'><\/script>"; 
document.getElemetsByClassName('HTML')[0].innerHTML += stringToAppend; 

注意我使用+=运营商到附加到已存在的内容中。

a += ba = a + b


如果你是开放的jQuery的并且只想内容到页面末尾追加相当于呼吁body选择的append方法:

$('body').append('<a href="'+posturl+'">'+posttitle+'</a><h2>'+posttitle+'</h2>  <span>'+postAuthor+'</span><span>'+postLabels+'</span><div>'+img[i]+'</div>'); 
+0

谢谢,但你可以给我的第一个代码与JQuery而不是JavaScript – abdel

+0

你已经在你的问题的第一部分代码。我不确定我是否明白这一点。 – matewka

+0

主要想法是我想添加脚本代码内容id =“myscript”与jquery模板上的一个div。你能帮我解决吗? – abdel