这是适当编写的插件。你需要认识到这里有嵌套循环,你需要通读所有的 cmets。我还提供了一个jsfiddle demo。
另外,顺便说一句,您应该知道这根本没有使用 JSON。 JSON 是一串序列化的数据。您正在使用一个 JS 数组文字,其中包含两个 JS 对象文字,每个文字都有两个属性。
JSON 看起来很相似,因为它借用了语法……但 JSON 是一个字符串。如果没有字符串,则当前上下文中没有 JSON。如果您不必解析它 - 它不是 JSON。
(function ($) {
$.fn.generateText = function (options) {
// `generateText` is a function, which is its own scope and context for `this`
// Your settings (which do not actually contain JSON, by the way...)
var settings = $.extend (
{
json: [
{
id: 1,
name: 'Name',
},
{
id: 2,
name: 'Name2',
}
]
},
options
);
// In the function, `generateText`, `this` refers to the instance of jQuery which gets created when the plugin runs.
// It contains the collection of elements which matched the DOM query when you ran it. Plugins should operate on all
// DOM elements in the container, and return the entire collection for chaining. Since `$.fn.each` will iterate and returns
// the collection, we can use it and return its own return to accomplish both purposes
return this.each(function () {
// Now we're in a new function--one which is being run for every element which was in the collection. Inside of a function
// which is passed to `$.fn.each`, `this` refers to the raw DOM element being acted on for that iteration. We'll need to use
// it in another scope a little lower, so we need to alias it:
var ele = this;
// `$.each` is a little different than `$.fn.each`. We pass it two args--the thing to iterate (the array from your so-called
// JSON in this case), and a function to run on each of the items as we iterate.
$.each(settings.json, function () {
// Ok, in a new function, so a new scope for `this` (...good thing we aliased the above `this` as `ele` since we need to use it.)
// In this function `this` is the item from `settings.json` on the current iteration. You want things from it, and you want to
// append to the element form above. Remember, `ele` was the raw DOM element for that iteration. Now we pass it to jQuery to
// become a new collection which we can act on by appending a new div with some data attrs which come from the current item
$(ele).append(
$('<div />')
.addClass('text')
.data('text-id', this.id)
.data('text-name', this.name)
);
});
});
}
}(jQuery));