data-text-name
어떤 <div class="text">
을 표시하지 않습니다 ( 사람이 나에게
당신이 제시 한 것처럼 각 기능 TE 변경 한 도와 드릴까요하지만 여전히 작동하지 않는 것은 마찬가지로 작성된 플러그인입니다 적합. 당신은 여기에 루프가 중첩되어 있음을 인식해야하고, 모든 코멘트를 읽을 필요가 제쳐두고, 당신은이 아니라는 것을 알아야한다. 또한, 또한 jsfiddle demo.
를 제공하고 있습니다 JSON은 직렬화 된 데이터 문자열이며 JS 배열을 사용하고 있습니다. 리터럴에는 각각 두 개의 속성이있는 두 개의 JS 객체 리터럴이 들어 있습니다. JSON은 구문을 빌리기 때문에 비슷해 보이지만 JSON은 STRING입니다. 문자열이 없으면 현재 컨텍스트에 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));
작동하지 않는 방법에 대한 자세한 설명 (오류 메시지 포함)을 제공하십시오. 샘플 입력과 관련 예상 출력도 제공해야합니다. –
글쎄, 한 가지만'settings.json.id'는 유효하지 않습니다. 아마도'settings.json [0] .id'가 필요하거나'$ (settings.json) .each (function() {...}); '를 사용해야했을 것입니다. 그 each() 함수에는 많은 특이한 것들이 있습니다. – Jason