2
我想在Javascript和jQuery中創建自定義選項卡小部件。我已經創建了標籤對象,但在分配單擊事件時遇到問題,請查看代碼。我附加了事件,但它僅對最後一個對象起作用。有人可以建議更好的方法來做到這一點Jquery on()點擊自定義對象上的函數
function TabTitleBox(TabName){
this.SelectedBox = 0;
this.TitleBoxContainer = $('<div>'+TabName+'</div>');
this.TitleBoxContainer.addClass("STATSTab");
this.TitleBoxContainer.addClass("UnSelectedTab");
this.TitleBoxContainer.on('mouseenter',function(){
CurrentColor = $(this).css('background-color');
var t = tinycolor(CurrentColor);
var NewColor = tinycolor.saturate(t,50);
$(this).css("background-color",NewColor);
}).on('mouseleave',function(){
$(this).removeAttr('style','background-color');
});
this.SelectTab = function(){
if(this.SelectedBox == 0){
$(this.TitleBoxContainer).removeClass("UnSelectedTab");
$(this.TitleBoxContainer).addClass("SelectedTab");
this.SelectedBox = 1;
}
}
this.RemoveStyle = function(){
$(this.TitleBoxContainer).removeAttr('style','background-color');
}
this.UnSelectTab = function(){
if(this.SelectedBox == 1){
$(this.TitleBoxContainer).removeClass("SelectedTab");
$(this.TitleBoxContainer).addClass("UnSelectedTab");
this.SelectedBox = 0;
}
}
return this;
}
TabContainer = new Array();
TabContainer.push(new TabTitleBox("Is first tab"));
TabContainer.push(new TabTitleBox("Is Second tab"));
TabContainer.push(new TabTitleBox("Is Third tab"));
TabContainer.push(new TabTitleBox("Is Fourth tab"));
for(var x = 0; x < TabContainer.length ; x++){
Tab = TabContainer[x];
$('body').append(Tab.TitleBoxContainer);
$(Tab.TitleBoxContainer).on('click', function(){
if(Tab.SelectedBox == 1){
Tab.UnSelectTab();
Tab.SelectedBox = 0;
}else{
Tab.SelectTab();
Tab.SelectedBox = 1;
}
Tab.RemoveStyle();
});
}
找出解決方案感謝我的代碼中完成的答案更改如下。鏈接可以在這裏http://skondgekar.comeze.com/Test.php
TabContainer = new Array();
TabContainer.push(new TabTitleBox("Is first tab"));
TabContainer.push(new TabTitleBox("Is Second tab"));
TabContainer.push(new TabTitleBox("Is Third tab"));
TabContainer.push(new TabTitleBox("Is Fourth tab"));
var funcs = [];
for(var x = 0; x < TabContainer.length ; x++){
Tab = TabContainer[x];
funcs[x] = (function(Tab){
return function(){
$(Tab.TitleBoxContainer).on('click', function(){
if(Tab.SelectedBox == 1){
Tab.UnSelectTab();
}else{
Tab.SelectTab();
}
Tab.RemoveStyle();
});
}
})(Tab);
funcs[x]();
$('body').append(Tab.TitleBoxContainer);
}
進入循環前有什麼TabContainer.length的值的例子,並最終在x右括號?是否所有4個選項卡添加到身體?你用什麼來驗證事件是否被附加? – user1853181
我能夠在我的瀏覽器中獲取元素,並且能夠使用alert事件使用click事件獲取他們的innerHTML,但是通過點擊元素它只改變最後一個對象的類而不是被點擊的對象 –
您需要實現一個正確關閉你的點擊函數,或者嘗試用$(this)而不是Tab來引用活動對象,因爲當執行點擊函數時,Tab引用最後一個處理的Tab。 – user1853181