jQuery appendTo,带有来自JSON的属性

时间:2013-10-02 21:15:03

标签: jquery appendto

$.each(tools, function (i, tool) {
    $("<img>", tool).appendTo($toolbar);
});

//define toolset (JSON, e.g. from database)...
var tools = [{
    "data-id": 1,
    alt: "sun",
    title: "sun",
    src: "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Sunny.png",
    "data-description": "sun in photo"
}, {
    "data-id": 2,
    alt: "snow",
    title: "snow",
    src: "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Thermometer_Snowflake.png",
    "data-description": "snow in photo"
}, {
    "data-id": 3,
    alt: "cloud",
    title: "cloud",
    src: "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Overcast.png",
    "data-description": "cloud in photo"
}, {
    "data-id": 4,
    alt: "rain",
    title: "rain",
    src: "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Night_Rain.png",
    "data-description": "rain in photo"
}];

我正在看一些我第一次看到的jQuery。我看到我相信每个工具会发生什么,并且使用JSON中描述的适当属性创建img标记。如果是这样的话,我认为这非常简洁,我想知道在手册或API文档中可能会更详细地描述这种技术吗?

提前致谢...

1 个答案:

答案 0 :(得分:1)

代码:

$.each(tools, function (i, tool) {
    $("<img>", tool).appendTo($toolbar);
})

让我们分块:


$.each(tools, function (i, tool) { }); - jQuery each

这与:

相同
for(i = 0; i < tools.length; i++) {
    var tool = tools[i];
}

$("<img>", tool) - jQuery element creator

这与:

相同
$("<img data-id='' src='' alt='' title='' data-description=''>");

并填写每组参数,例如,第一个tool(太阳)将是:

$("<img data-id='1' src='http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Sunny.png' alt='sun' title='sun' data-description='sun in photo'>");

与:

相同
$("<img>").attr({
    "data-id": 1,
    "alt": "sun",
    "title": "sun",
    "src": "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Sunny.png",
    "data-description": "sun in photo"
});

相同
$("<img>", {
    "data-id": 1,
    "alt": "sun",
    "title": "sun",
    "src": "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Sunny.png",
    "data-description": "sun in photo"
});

这正是$("<img>", tool)的全部内容


appendTo($toolbar); - jQuery appendTo

只需将tools数组中每个对象的结果附加到$toolbar中,这可能是一个简单的<div>