单击后如何更改按钮的attr和id?用jquery? [英] How to change the attr and id of a button after clicking? using jquery?
问题描述
我正在尝试按钮随时更改其onclick和id属性。但是对于一些人来说,我只能在第一次更改这些属性。
I am trying to have a button change its onclick and id attributes on the fly. But for some ready, I'm only able to change these attributes the first time.
$("#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");
});
以下是示例。我看到id已经改变了,但是调用了错误的onclick函数。
Here is the example. I see that the id has changed, but the wrong onclick function is been called.
我想要完成的是:
- 用户在表单上输入一些东西,然后点击搜索 - >应该返回一些数据
- 如果有数据,那么按钮应该更改其ID和onclick
- 如果没有,保持不变
推荐答案
您在id更改为 btn2
之前附加事件,因此 $(#btn2)
是一个空集合。在第一个回调中绑定click处理程序,如下所示:
You are attaching the event before the id has changed to btn2
, so $("#btn2")
is an empty collection. Bind the click handler in the first callback, like so:
$("#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");
});
});
这是一个演示: http://jsfiddle.net/73zA2/
或者,您可以将事件处理委托给元素的祖先:
Alternatively, you can delegate event handling to an ancestor of the element:
$("#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");
});
以下是该方法的演示: http://jsfiddle.net/2YKFG/
Here is a demonstration of that approach: http://jsfiddle.net/2YKFG/
这篇关于单击后如何更改按钮的attr和id?用jquery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!