我正在使用jquery 1.9.1,我正在尝试开发一个插件。问题是该插件无法正常工作。这是代码:
;(function($) {
$.fn.single = function() {
return this.each(function(){
// Get the instance
var element = $(this);
// Resize the "data-target" divs
element.load(function(){
changeCSS(element);
});
// Bind the method to the resize window event
$(window).bind("resize", function(){
changeCSS(element);
});
});
};
// function to resize all the "data-target" divs
function changeCSS(element) {
// Grab the screen resolution
var windowWidth = $(window).width();
var windowHeight = $(window).height();
// Count how many targets the div has
var targetsSize = $("[data-target]").size();
// Resize the parent div
$(element).css({
"width" : windowWidth,
"height": windowHeight * targetsSize
});
// Resize all the targets div
$(element + "> div[data-target]").each(function(){
$(this).css({
"width" : windowWidth,
"height": windowHeight
});
});
}
})(jQuery);
我在文档上这样称呼它:
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/single-0.1.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#single").single();
});
</script>
控制台没有问题。我做错了什么?
答案 0 :(得分:2)
我认为这是因为你滥用了方法 .load 。如果你看一下jQuery文档,它的目的是:
.load():从服务器加载数据并放置返回的HTML 进入匹配的元素。
删除行element.load(function ...
,只需调用你的changeCSS函数,你已经在Document.Ready上加载了这个扩展名
return this.each(function () {
// ...
changeCSS(element); // <-- just run the function right away
// ... etc
});
答案 1 :(得分:0)
通常在声明函数之前调用函数是不好的做法。为了使你的插件正确,你最好从头开始正确地构建它。除此之外,正如@mcpDESIGNS指出的那样,你错误地使用了 .load 方法。此外,如果你解释一下你在这里想要帮助到底是什么,这将是有用的。
要开始制作jQuery插件,请尝试查看jQuery here中的文档,或者查看this教程。
这是首选结构:
(function($) {
// Declare your methods at the beginning of your plugin
var yourMethods = {
'methodOne' : function() {
},
'methodTwo' : function() {
}
};
$.fn.pluginName = function() {
return this.each(function() {
});
}
}(jQuery));
答案 2 :(得分:0)
而不是:
element.load(function(){
changeCSS(element);
});
我做了:
changeCSS(element);
而且......而不是:
$(element + "> div[data-target]")
我做了:
$(element).children('div[data-target]')
现在插件正在执行,没有错误或错误。 谢谢伙计们!