簡體   English   中英

如何在JSON字符串中包含Javascript字符串構造函數?

[英]How can I include a Javascript string constructor in a JSON string?

我正在構建Jquery Mobile列表視圖的模板。 為了使模板完全通用,我需要傳遞listitem文本。 所以目前我的listview配置看起來像這樣:

<ul data-role="listview" data-create="false" class="template" data-config='{
    "type":"listview",
    "data":"getRetailers",
    "custom_classes":["embedded_filter updateResults f-875","nMT pickList f-875 widget_listview","f-n",""],
    "lib":"static_listview.html",
    "tmp":"tmp_listview_inset",
    "lang":"locale_search",
    ...
    }'></ul>

我的問題是如何為列表項文本包含Javascript構造函數。 應該是以下內容:

inv.company+', '+ inv.zip + ', ' + inv.city

但是像這樣插入它:

...
"text":"inv.company+', '+ inv.zip + ', ' + inv.city"
}

不起作用。

問題
如何在JSON中包含Javascript構造函數?

試試這個代碼:

"text":"'"+ inv.company+ "', '"+ inv.zip + "','" + inv.city+ "'";

好。 不好,但是可以工作:

1)在我的JSON中,我只傳遞了一個函數名稱,如下所示:

<ul data-role="listview" data-create="false" class="template" data-config='{  
    "type":"listview",
    "data":"getRetailers",
    "custom_classes":["embedded_filter updateResults f-875","nMT pickList f-875 widget_listview","f-n",""],
    "lib":"static_listview.html",
    "tmp":"tmp_listview_inset",
    "lang":"locale_search",
    "text":"buildRetailers",
    ...
}'></ul>

2)然后在我的腳本中,將buildRetailers添加到我的dynoData模塊中:

var dynoData = {
    ...
    buildRetailers: function (inv) {
        return inv.company+', '+ inv.zip + ', '+ inv.city;
    },
    ...
}

3)並從我的listview字符串生成器中調用它:

....
listItem = listItem.replace( widget.options.re_theme, li_theme );
listItem = listItem.replace( widget.options.re_iconpos, li_iconpos );
listItem = listItem.replace( widget.options.re_icon, li_icon );
// call the function to return the list item text
listItem = listItem.replace( widget.options.re_text, dynoData[ li_text ](inv) );

因此,我似乎無法在JSON配置中傳遞函數字符串,因此我需要添加一個函數來構造所需的函數。 如果有人知道更好的方法,請發布。 我將進行測試。

您不能僅傳遞inv對象的對象文字版本是什么。

"text" : {
    "company": "some value here",
    "zip": "another value here",
    "city": "another value"
}

通常,您會這樣做:

"text": function(){ return inv.company+', '+ inv.zip + ', ' + inv.city }

但我不確定是否能奏效。 您仍然可以嘗試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM