javascript - 从JSON请求中获取HTML属性值

时间:2014-10-02 10:46:57

标签: javascript jquery json

我有博客帖子的JSON请求结果。

// API callback
posts(
{
    "version": "1.0",
    "encoding": "UTF-8",
    "entry":
    {
        "title":
        {
            "type": "text",
            "$t": "Vimeo Embed Video Post"
        },
        "content":
        {
            "type": "html",
            "$t": "<span data-format=\"video-post\"><\/span><iframe allowfullscreen=\"\" frameborder=\"0\" height=\"281\" mozallowfullscreen=\"\" src=\"\/\/player.vimeo.com\/video\/107469289\" webkitallowfullscreen=\"\" width=\"500\"><\/iframe> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod<br \/>tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,<br \/>quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo<br \/>consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse<br \/>cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non<br \/>proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        },
    }
});

"content"内,您可以看到<span data-format="video-post"></span>。我希望通过javascript从data-format atrribute获取价值。

2 个答案:

答案 0 :(得分:2)

<强>更新

试试这个......

function posts(data) {
   var formatData = $(data.entry.content['$t']).data('format');
}

更新#2

如果您的数据对象或其任何属性/子属性可能未定义,则以下是更安全的版本:

function posts(data) {
   var formatData = data 
      && data.entry 
      && data.entry.content 
      && data.entry.content['$t'] 
      && $(data.entry.content['$t']).data('format') || '';
   if (formatData!='') { //If has value
      // ... have something to do about it
   } 
}

JSFiddle

答案 1 :(得分:0)

试试这个......

$(variable.entry.content['$t']).data('format');

其中variable是post方法的参数。