jq动态增加的button标签click回调失效的问题,即动态增加的button标签绑定事件$("button.class").click(function)无效...

本文介绍了一种针对新增页面元素的有效事件监听方法。通过使用$(document).on()方法,可以实现在DOM元素动态添加后仍能正常响应事件的目标。具体示例为文字显示与隐藏的切换功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于新增加的页面元素,改变了页面结构,如果是使用老办法$("button.class").click(function)去监听新的button标签事件,会失效。

笔者的应用是文字的显示和隐藏之间的切换,给出我的代码:

解决办法:

$(document).on("click",".showPwd",function () {
//                alert("show now:" + );
                $(this).parent().html(
                        $(this).attr("key")+'  '+
                        '<button class="btn btn-default btn-sm hidePwd" key="'+$(this).attr("key")+'"><span class="glyphicon glyphicon-eye-close"></span></button>');
});

$(document).on("click",".hidePwd",function () {
                //alert("show now");
                $(this).parent().html('<button class="btn btn-default btn-sm showPwd" key="'+$(this).attr("key")+'"><span class="glyphicon glyphicon-eye-open"></span></button>');
});

 

转载于:https://www.cnblogs.com/alanleung/p/6837424.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值