我有一个函数可以在对话框标题中创建按钮元素。但是,click事件会附加到所有按钮而不是当前按钮。JQuery单击事件附加到多个元素
_createTitlebarButtons : function(){
for (var each in this.options.titlebarButtons) {
var self = this,
props = this.options.titlebarButtons[each];
if (!props.icon){ props.icon = ""}
if (!props.name){ props.name = "button-"+each.toString()}
if (!props.click){ props.click = function(){} }
if (!props.text){ props.text = "" }
var curButton = $("<button type='button' id='btn-"+each+"' ></button>").button({
type: "button",
label: $("<a>").text(props.text).html(),
icon: props.icon,
showLabel: false
})
.attr("name", props.name)
.css("right", 3+22*(Number(each)+1))
.appendTo(this.uiDialogTitlebar)
.on("click", function(event) {
event.preventDefault();
props.click.apply(self.element[ 0 ], arguments);
});
this._addClass(curButton, "ui-dialog-titlebar-close");
}
},
所有图标和类都可以工作。但是,click事件会附加到所有按钮而不是一个按钮。所以如果我有多个按钮,点击事件对所有按钮都是一样的。它将成为最后一个按钮的点击事件。所以:
titlebarButtons : [
{
name: "button1",
text: "tooltip",
icon: "ui-icon-heart",
click:function(){
console.log("Button1 Clicked");
console.log(this);
}
},
{
name: "button2",
text: "tooltip",
icon: "ui-icon-close",
click:function(){
console.log("Button2 Clicked");
console.log(this);
}
}
]
将创建2个按钮,但点击时他们都将说:“Button2的被点击的”,而第一个应该说“Button1的点击”。
编辑:由于范围问题,不得不使用$ .each而不是for循环。
$.each(this.options.titlebarButtons, function(index){
console.log(this);
var props = this;
if (!props.icon){ props.icon = ""}
if (!props.name){ props.name = "button-"+index}
if (!props.click){ props.click = function(){} }
if (!props.text){ props.text = "" }
var curButton = $("<button type='button' ></button>").button({
type: "button",
label: $("<a>").text(props.text).html(),
icon: props.icon,
showLabel: false
})
.attr("name", props.name)
.css("right", 3+22*(Number(index)+1))
.appendTo(self.uiDialogTitlebar)
.on("click", function(event) {
event.preventDefault();
props.click.apply(self.element[ 0 ], arguments);
});
self._addClass(curButton, "ui-dialog-titlebar-close");
})
在这种情况下,可以使用'。点击()''对比。对( “点击”)'。我发现前者在这种情况下工作得更好。 – Twisty
作用域 - 你的'self'在循环之外,因此在调用click事件时变为循环的最后一个元素。 “但它是在循环内部声明的”,你说 - 也许,但范围仍然在外面,因为这是JS变量的工作原理。 –