我试图让一个按钮动态更改其onclick和id属性。但是,为了准备就绪,我只能在第一次更改这些属性。
$("#btn1").click(function () {
window.alert("im changing id to btn2 and ho ho ho");
$("#btn1").val("ho ho ho");
$("#btn1").attr("id", "btn2");
});
$("#btn2").click(function () {
window.alert("im changing id to btn1 and hey hey");
$("#btn2").val("hey hey");
$("#btn2").attr("id", "btn1");
});
Run Code Online (Sandbox Code Playgroud)
这是例子。我看到ID已更改,但是调用了错误的onclick函数。
我要完成的工作如下:
您是在ID更改为之前附加事件btn2,因此$("#btn2")是空集合。将点击处理程序绑定到第一个回调中,如下所示:
$("#btn1").click(function () {
window.alert("im changing id to btn2 and ho ho ho");
$("#btn1").val("ho ho ho");
$("#btn1").attr("id", "btn2");
$("#btn2").unbind("click").click(function () {
window.alert("im changing id to btn1 and hey hey");
$("#btn2").val("hey hey");
$("#btn2").attr("id", "btn1");
});
});
Run Code Online (Sandbox Code Playgroud)
这是一个演示:http : //jsfiddle.net/73zA2/
另外,您可以将事件处理委托给元素的祖先:
$("#btn1").parent().on("click","#btn1", function () {
window.alert("im changing id to btn2 and ho ho ho");
$("#btn1").val("ho ho ho");
$("#btn1").attr("id", "btn2");
})
.on("click","#btn2",function () {
window.alert("im changing id to btn1 and hey hey");
$("#btn2").val("hey hey");
$("#btn2").attr("id", "btn1");
});
Run Code Online (Sandbox Code Playgroud)
这是该方法的演示:http : //jsfiddle.net/2YKFG/
| 归档时间: |
|
| 查看次数: |
9543 次 |
| 最近记录: |