creating json from DOM elements using jQuery

前端 未结 3 1588
终归单人心
终归单人心 2021-01-03 03:39

If I have the following DOM elements

content1
content2

how, usi

相关标签:
3条回答
  • 2021-01-03 03:46
    var data = $('div.item').map(function(){
        return {
            classname: 'item',
            content: $(this).text()
        };
    }).get();
    

    DEMO: http://jsfiddle.net/nDE7e/

    0 讨论(0)
  • 2021-01-03 03:46

    http://jsfiddle.net/24JjD/

    var datas = [{ 
        'classname': 'item',
        'content': 'content1'
        }, {
        'classname': 'item',
        'content': 'content2'
        }
    ];
    
    $.each(datas, function(key, value) {
        $('body').append('<div class="'+value.classname+'">'+value.content+'</div>');
    });​
    

    Correct answer :

    http://jsfiddle.net/tS9r5/

    var datas = [];
    
    $('div.item').each(function() {
       var data = { 
           classname: this.className, 
           content: $(this).text()
       };
       datas.push(data);
    });
    
    console.log(datas);
    

    0 讨论(0)
  • 2021-01-03 03:55

    You can loop over the item divs and add objects to an array.

    var items = new Array();
    
    $("div.item").each(function() {
       var item = {classname: this.className, content: $(this).text()};
       items.push(item);
    });
    
    0 讨论(0)
提交回复
热议问题