gpt4 book ai didi

javascript - 动态激活自定义类按钮

转载 作者:行者123 更新时间:2023-11-30 13:21:52 24 4
gpt4 key购买 nike

我正在使用 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)');

最佳答案

您需要设置事件委托(delegate),以便事件处理程序识别动态生成的元素。基本原则是你在一个静态元素上设置事件处理程序(一个在页面加载时存在,并且将永远存在的元素),它将包含你想要触发回调函数的所有元素 - 如果没有如果您的 HTML 中定义了合适的容器元素,您可以使用 body,但越具体越好。

如果您使用的是 jQuery 1.7+,您将需要 .on()功能。由于您要绑定(bind)多个事件,因此最好使用事件映射语法:

$('body').on({
mousedown: function() {

},
mouseup: function() {

},
...
}, '.fg-button:not(.ui-state-disabled)');

请注意,hover 不是实际事件,该函数只是绑定(bind)到两个不同事件(mouseentermouseleave)的简写).

如果您使用的是 jQuery 1.7 之前的版本,请查看 .delegate()函数代替。

关于javascript - 动态激活自定义类按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9992583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com