如何将json stringify输出转换为字符串并将其显示给textarea

时间:2015-08-23 06:22:47

标签: javascript jquery json

我的代码是:

$("#Button").on('click', function () {
     var rowindexes = $('#jqxgrid').jqxGrid('getselectedrowindexes');
     var boundrows = $('#jqxgrid').jqxGrid('getboundrows');
     var selectedrows = new Array();
     for(var i =0; i < rowindexes.length; i++)
     {
         var row = boundrows[rowindexes[i]];
         selectedrows.push(row);
     }

    var a=JSON.stringify(selectedrows);
    $(jQuery.parseJSON(a)).each(function() {  
    var ID = this.EmployeeID;
    var TITLE = this.Title;
    //alert(ID+TITLE);

    $('#comment').val(ID).split('\n');

}); 

我使用alert on javascript此代码正常工作显示此数据, 当我使用textarea显示此数据时,此代码无法正常工作 只有一个数据可以显示给我 请给我一个解决这个问题的方法 感谢

2 个答案:

答案 0 :(得分:0)

因为当$('#comment').val(ID)#comment中的当前内容更改为ID时,所以在forEach迭代后,#comment只显示最后ID

您可以定义一个字符串,并在每次迭代中将数据附加到该字符串,然后在处理每个数据时将字符串设置为#comment

$("#Button").on('click', function () {
     var rowindexes = $('#jqxgrid').jqxGrid('getselectedrowindexes');
     var boundrows = $('#jqxgrid').jqxGrid('getboundrows');
     var selectedrows = new Array();
     for(var i =0; i < rowindexes.length; i++)
     {
         var row = boundrows[rowindexes[i]];
         selectedrows.push(row);
     }

    var comments = '';
    // As Felix Kling says, you don't have to convert the selectedrows to
    // string then convert them back. just use $.each(selectedrows, ....
    // is enough.
    $.each(selectedrows, function() {  
        var ID = this.EmployeeID;
        var TITLE = this.Title;
        //alert(ID+TITLE);

        // Append new comment to the comments string.
        comments = comments + ID + TITLE + '\n';
    });

    // Set the `#comment`'s value to comments after all comment is append to comments.
    $('#comment').val(comments);
});

演示:

// A fake data that has attr EmployeeID and Title to fit the logic in $.each
var fake = [
  {EmployeeID: 1, Title: 'a'},
  {EmployeeID: 2, Title: 'b'},
  {EmployeeID: 3, Title: 'c'},
  {EmployeeID: 4, Title: 'd'},
];
  

$("#Button").on('click', function () {   
  var comments = '';
  $.each(fake, function() {  
    var ID = this.EmployeeID;
    var TITLE = this.Title;
    //alert(ID+TITLE);
    comments = comments +  ID + TITLE + '\n';
  }); 
  $('#comment').val(comments);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<textarea id="comment"></textarea>
<button id="Button">show</button>

答案 1 :(得分:0)

试试这个

document.getElementById("comment").value = "ID";