javascript-从JSON请求获取HTML属性值 [英] javascript - get HTML attribute value from a JSON request

查看:118
本文介绍了javascript-从JSON请求获取HTML属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个博客帖子的JSON请求结果.

I have a JSON request result for a blogger post.

// 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属性中获取价值.

Inside the "content" you can see there is a <span data-format="video-post"></span>. I want to get value from data-format atrribute with javascript.

推荐答案

更新

尝试一下...

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

更新#2

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

In case if your data object, or any of it's properties/subproperties might be not defined, here is safer version:

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

这篇关于javascript-从JSON请求获取HTML属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆