【问题标题】:How to add a Array to a Javascript Variable如何将数组添加到 Javascript 变量
【发布时间】:2015-11-17 00:31:41
【问题描述】:

我认为对你们大多数人来说是一个简单的问题;-) 我有一个数组(来自 Sharepoint 列表),如果我通过 .html 将它写入 DIV,这个数组会显示如下:

{name="Drittes Kapitel"text="uiuiui"value="45.0000000000000"}
{name="Ein anderer Titel"text="Ein zweiter Text"value="123.000000000000"}
{name="Ein Titel"text="Das ist der Text"value="256.000000000000"}

我将其放入 DIV 的代码如下:

function AddContent(name,text,value)
{    $("#meineListe").append('{name="'+ name + '"text="' + text + '"value="'+ value +'"}<br />');
                                
}

所以它显示了这个数组中的所有 3 个元素 但是如何将数组放入变量中? 如果我尝试

function AddElements(name,text,value)
{   MyElements = ('{name="'+ name + '"text="' + text + '"value="'+ value +'"}<br />');
	console.log(MyElements);
	$("#meineListe").html(MyElements);
                                
}

它只显示了它们的第一个条目...我不明白这里到底发生了什么。

完整代码(来自 sharepointhillbilly):

//this is where the script starts after the page is loaded
$(document).ready(function() { 

    GetMyListData();

});

function GetMyListData()
{
        //The Web Service method we are calling, to read list items we use 'GetListItems'
        var method = "GetListItems";
        
        //The display name of the list we are reading data from
        var list = "MyList";

        //We need to identify the fields we want to return. In this instance, we want the Name (Title),
        //Blog, and Picture fields from the Speakers list. You can see here that we are using the internal field names.
        //The display name field for the Speaker's name is "Name" and the internal name is "Title". You can see it can 
        //quickly become confusing if your Display Names are completely differnt from your internal names. 
        //For whatever list you want to read from, be sure to specify the fields you want returned. 
        var fieldsToRead =     "<ViewFields>" +
                                "<FieldRef Name='Title' />" +
                                "<FieldRef Name='treo' />" +
                                "<FieldRef Name='iz1y' />" +
                            "</ViewFields>";
                            
        //this is that wonderful CAML query I was talking about earlier. This simple query returns
        //ALL rows by saying "give me all the rows where the ID field is not equal to 0". I then 
        //tell the query to sort the rows by the Title field. FYI: a blank query ALSO returns
        //all rows, but I like to use the below query because it helps me know that I MEANT to 
        //return all the rows and didn't just forget to write a query :)
        var query = "<Query>" +
                        "<Where>" +
                            "<Neq>" +
                                "<FieldRef Name='ID'/><Value Type='Number'>0</Value>" + 
                            "</Neq>" +
                        "</Where>" +
                        "<OrderBy>" + 
                            "<FieldRef Name='Title'/>" +
                        "</OrderBy>" +
                    "</Query>";

        //Here is our SPServices Call where we pass in the variables that we set above
        $().SPServices({
                operation: method,
                async: false,  //if you set this to true, you may get faster performance, but your order may not be accurate.
                listName: list,
                CAMLViewFields: fieldsToRead,
                  CAMLQuery: query,
                      //this basically means "do the following code when the call is complete"
                    completefunc: function (xData, Status) { 
                        //this code iterates through every row of data returned from the web service call
                        $(xData.responseXML).SPFilterNode("z:row").each(function() { 
                            //here is where we are reading the field values and putting them in JavaScript variables
                            //notice that when we read a field value there is an "ows_" in front of the internal field name.
                            //this is a SharePoint Web Service quirk that you need to keep in mind. 
                            //so to read a field it is ALWAYS $(this).attr("ows_<internal field name>");
                            
                            //get the title field (Element Title)
                            var name = ($(this).attr("ows_Title"));
							var text = ($(this).attr("ows_treo"));
							var value = ($(this).attr("ows_iz1y"));
                            
                            //get the blog url, SharePoint stores a url in the form of <url><comma><description>
                            //We only want the <url>. To accomplish this we use the javascript "split" function
                            //which will turn <url><comma><description> into an array where the first element [0]
                            //is the url.   Catch all that? if you didn't this is another reason you should be
                            //a developer if you are writing JavaScript and jQuery :)
                            //var blog = ($(this).attr("ows_Blog")).split(",")[0];
                            
                            //same thing as the blog, a picture is stored as <url><comma><alt text>
                            //var pictureUrl = ($(this).attr("ows_Picture")).split(",")[0];
                            
                            //call a function to add the data from the row to a table on the screen
                            AddElements(name,text,value);
                            
                        });                
                    }
        });

}

// very simple function that adds a row to a table with the id of "speakerTable" 
// for every row of data returned from our SPServices call. 
// Each row of the table will display the picture of the speaker and
// below the speaker's picture will be their name that is a hyperlink
// to the speaker's blog.
function AddRowToTable(name,text,value)
{   MyElements = ('{name="'+ name + '"text="' + text + '"value="'+ value +'"}<br />');
	console.log(MyElements);
	$("#meineListe").html(MyElements);
                                
}
<!-- table where our listContent rows will go -->
<div id="meineListe"></div>

有什么建议吗?

我需要这个数组在一个 JS 变量中。 是否有另一种解决方案,如 .append 将数组添加到变量中?

【问题讨论】:

    标签: javascript jquery html arrays


    【解决方案1】:

    $('#meineList').append(item); 会将item 附加到您的id 为meineList 的元素中,而$('#meineList').html(item); 将用您传入的item 替换您元素中ID 为meineList 的任何html .

    我假设您为每个项目调用 AddContent()AddElements(),这就是为什么当您调用 AddElements() 时,它会显示您的第一个元素,然后将其替换为第二个元素,然后将其替换为第三个,因此仅显示您传递给它的最后一个元素。所以,你绝对应该使用AddContent() 函数,这样你的所有项目都会显示出来。

    要将传入的每个项目添加到数组中,您需要在函数外部创建一个数组,然后在每次调用函数时添加一个新元素。

    编辑:

    查看您的完整代码,应该为您要添加的每个元素调用您的 AddRowToTable() 函数,因此如果您在函数内部调用 .html(),您只会得到最后一个元素输出。

    相反,只需在 AddRowToTable() 函数中将元素添加到数组中,然后在 GetMyListData() 函数完成后打印出数组的内容。

    尝试将您的代码更改为这样的内容(为了更好的可读性,我删除了 cmets):

    var arr = [];
    
    $(document).ready(function() {
      GetMyListData();
      $('#meineList').html(arr.toString());
    });
    
    function GetMyListData() {
      var method = "GetListItems";
      var list = "MyList";
    
      var fieldsToRead = "<ViewFields>" +
        "<FieldRef Name='Title' />" +
        "<FieldRef Name='treo' />" +
        "<FieldRef Name='iz1y' />" +
        "</ViewFields>";
    
      var query = "<Query>" +
        "<Where>" +
        "<Neq>" +
        "<FieldRef Name='ID'/><Value Type='Number'>0</Value>" +
        "</Neq>" +
        "</Where>" +
        "<OrderBy>" +
        "<FieldRef Name='Title'/>" +
        "</OrderBy>" +
        "</Query>";
    
      $().SPServices({
        operation: method,
        async: false,
        listName: list,
        CAMLViewFields: fieldsToRead,
        CAMLQuery: query,
        completefunc: function(xData, Status) {
          $(xData.responseXML).SPFilterNode("z:row").each(function() {
    
            var name = ($(this).attr("ows_Title"));
            var text = ($(this).attr("ows_treo"));
            var value = ($(this).attr("ows_iz1y"));
    
            AddRowToTable(name, text, value);
          });
        }
      });
    }
    
    function AddRowToTable(name, text, value) {
      arr.push({'name': name, 'text': text, 'value': value});
    }
    

    【讨论】:

    • okey... 但这并没有改变任何东西... :-/ 它只是向我展示了第一个条目
    • 查看我的编辑。我认为您仍然试图在错误的地方使用.html()
    • 好的,它可以工作 ;-) 非常感谢 - 现在我必须与 sharepoint / 一起战斗......但那是另一个故事要完成,我的 arr.push:arr.push(' {id:'+id+',label:"'+name+'",description:"'+desc+'",value:"'+value+'",color:'+color+'}');
    【解决方案2】:

    您的AddRowToTable 应该真正使用$('#meineListe').append() 而不是$('#meineListe').html()。这会将数据追加到其中的现有 html 中,而不是仅仅覆盖它(使用 .html())。

    【讨论】:

    • with .append 它可以工作,但最后我不希望这个数组在 HTML 中 - 我需要将整个数组放在 JS 变量中... $('#meineListe').html () 只是为了让我现在显示这个变量 MyElements 中的内容......
    • 如果您要做的是创建一个数组,然后向其中添加项目,那么您应该阅读 Array.push 函数。 var arr = []; 然后arr.push({name: "Borat", age: 42});
    • 嗨 Ronan,Andrews 解决方案对我来说很好,不幸的是我现在遇到了分号问题,但实际上它与 arr.push 一起使用,正如您所描述的那样......感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    相关资源
    最近更新 更多