如何使用JavaScript动态创建div?

时间:2017-02-10 16:15:07

标签: javascript html

我希望以访问import re text = "Absolutely<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E64> Friendship goals exceeded here!! Sydney, Melbourne, Connecticut &amp; South Carolina<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E61>\r\n" pattern = "<.*?>(?!<)" print re.findall(pattern, text) #['<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E64>', '<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E61>'] 数据的方式创建divs,并在每次创建新JSON时显示所有数据。我通过div获得了第一个div显示信息。这是我到目前为止所得到的:

JSON

2 个答案:

答案 0 :(得分:0)

我不知道这是否是一种基本的javascript方式...但我使用jquery将数据添加到每个新的div元素

data = {"obj" : [{"name" : "John"}]}

返回对象的Json

$.each(data.obj, function(i, message){
    var htmlMessage = "";

    htmlMessage += "<div>";
    htmlMessage += "<p>";
    htmlMessage += "<span>";
    htmlMessage += message.name;
    htmlMessage += "</div>";
    htmlMessage += "</p>";
    htmlMessage += "</span>";

    $("#body")[0].innerHtml += htmlMessage;
});

答案 1 :(得分:0)

您可以创建用于创建元素的自定义函数。例如:

// creating elements function
function createEl(config){
    config = config || {};
    if(!config.type) throw new Error('config type required!');

    var new_el = document.createElement(config.type);
    // check text param
    if(config.text) new_el.textContent = config.text;

    // maybe check for other element attributes (id, class, etc)
    // ...

    return new_el;
}

// some code
// ...
var obj = {
    id: 'id',
    nombre: 'pepe',
    telefono: '6691296347'
};

var body = document.getElementsByTagName('body')[0];
var div = createEl({ type: 'div' });
var p = createEl({ type: 'p', text: 'nombre: '});
var span = createEl({ type: 'span', text: obj.nombre});
// other elements
// ...

// and then append
p.appendChild(span);    
div.appendChild(p);
body.appendChild(div);
// ...