我正在使用javascript来动态创建按钮,其中我设置了所有属性并将其显示在我的页面上。然后使用jQuery实现悬停并单击逻辑来更改按钮类的布局。当按钮被创建时,它的类布局就是它应该是的,但是当它悬停或点击时,它不会像在运行时创建它时那样改变。动态激活自定义类按钮
的javascipt的代码:
function createbutton()
{
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("class", "fg-button ui-state-default ui-corner-all");
btn.setAttribute("value", "click!");
btn.setAttribute("onclick", "createbutton()");
theParent = document.getElementById("content");
theParent.appendChild(btn);
}
$(function(){
//all hover and click logic for buttons
$(".fg-button:not(.ui-state-disabled)")
.hover(
function(){
$(this).addClass("ui-state-hover");
},
function(){
$(this).removeClass("ui-state-hover");
}
)
.mousedown(function(){
$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
if($(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active')){ $(this).removeClass("ui-state-active"); }
else { $(this).addClass("ui-state-active"); }
})
.mouseup(function(){
if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button, .fg-buttonset-multi .fg-button')){
$(this).removeClass("ui-state-active");
}
});
});
在HTML:
<input type="button" onclick="createbutton()" value="CLICK" >
<div id="content">
</div>
有没有我应该设置另一个属性,或者我应该做别的事情来激活jQuery函数创建按钮时?
编辑(更新功能):
$('body').on(
{
mousedown: function()
{
$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
if($(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active')){ $(this).removeClass("ui-state-active"); }
else { $(this).addClass("ui-state-active"); }
},
mouseup: function()
{
if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button, .fg-buttonset-multi .fg-button')){$(this).removeClass("ui-state-active");}
},
mouseenter: function()
{
$(this).addClass("ui-state-hover");
},
mouseleave: function()
{
$(this).removeClass("ui-state-hover");
}
}, '.fg-button:not(.ui-state-disabled)');
你应该通过JSLint运行你的JS,并考虑你得到的建议。 – ANeves 2012-04-03 12:49:29