我必须在HTML中使用代码:
$(document).ready(function(){
jQuery(".test").each(function(index) {
jQuery(this).someObject({attr : index});
});
});
someObject看起来像 (参见Edit2.5)
我在该对象上有一个onclick事件。如果单击它,它将执行函数“someFunc”(它确实如此)。
问题是,它仅警告最后一个索引。假设我有5个带有“.test”类的对象。如果我单击它创建的任何someObject,它将始终警告最后一个对象的索引。
修改 好的,我忘了一个重要的细节。在'someObject'中,我创建了一个包含表的div,每个td都有一个onclick函数,它将执行函数'someFunc'。
如果我将'someFunc'私有化:
var someFunc = function(){
alert(settings.attr);
}
浏览器会创建一个错误“Object expected”。
Edit2.5 :整个'someObject'
(function($){
$.fn.someObject = function(options){
// Set default Settings
var settings = {
dpButtonImage : "images/icon.png",
dpButtonClass : "Button",
openOnFocus : false
};
$.extend(settings, options);
var someFunc = function(){
alert(settings.arr);
}
var displayPicker = function(target, counter){
var offset = jQuery(target).offset();
var height = jQuery(target).outerHeight();
drawPicker(target, offset, height);
}
var drawPicker = function(target, offset, height){
if (!document.getElementById("Wrapper")){
$("body").append(function(){
return $("<div></div>")
.addClass("Wrapper")
.attr({
id : "Wrapper"
})
.css({
display : "none"
});
});
}
// Create container element.
var container = $("#Wrapper");
// Move the wrapper to the proper coordinate.
container.css({
top: offset.top + height + 1,
left: offset.left
});
// Toggle the visibility.
if (container.is(":visible")){
container.hide();
} else {
container.show();
}
refreshPicker2();
}
refreshPicker2 = function(){
var html = $("<table><tbody><tr><td>Test</td></tr></tbody></table>");
html.find("td").click(someFunc);
$("#Wrapper").html(html);
}
return this.each(function(){
var target = this;
var $target = $(this);
var counter = $.event.guid++;
var readonly = $(target).attr("readonly");
target.settings = settings;
if (target.settings.openOnFocus){
$target.bind("focus", function(){
if (!readonly){ displayPicker(target, counter); }
});
}
// Append dpButton if it doesn't already exist.
if (!document.getElementById('dpButton_'+counter)){
$target.after(function(){
return $("<img />")
.addClass(target.settings.dpButtonClass)
.attr({
src : target.settings.dpButtonImage,
alt : "testicon",
id : "dpButton_"+counter
})
.bind("click", function(){
if (!readonly){ displayPicker(target, counter);}
return false;
});
});
}
});
};
})(jQuery);
答案 0 :(得分:0)
如果没有var
,您将someFunc
创建为全局函数,并且每次都会被覆盖,所以:
someFunc = function(){
alert(settings.attr);
}
应该是:
var someFunc = function(){
alert(settings.attr);
}