如何在表格中显示时,将JSON文件中的URL值设置为超链接?
JSON
{
"one": "http://urltovideo.mp4",
"two": "The second list item",
"three": "The third list item"
}
的jQuery
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<div class='panel panel-default'><div class='panel-heading'>" + key + "</div><div
class='panel-body'><a href=''>" + val + "</a></li></div></div>" );
});
$( "<ol/>", {
"class": "my-new-list",
html: items.join( "" )
}).fadeIn(900).appendTo( "body" );
});
答案 0 :(得分:0)
您需要检查val
是否包含链接:
$.each( data, function( key, val ) {
var link = (val.indexOf('http') > -1) ? '<a href="' + val + '">' + val + '</a>' : val;
items.push( '<div class="panel panel-default"><div class="panel-heading">' + key + '</div><div
class="panel-body">' + link + '</li></div></div>');
});
此外,对于更干净的代码,您应该使用"
对{J}字符串等class="..."
和'
等HTML属性进行操作,例如:'<a href="' + val + '">'
请参阅jsFiddle