我正在尝试动态更改其ID来更改按钮的功能。
<srcipt>
$("#old-id").click(function func_P(){
//Some code
this.id = "new-id";
});
$("#new-id").click(function func_Q(){
// some other code
});
$("#clear").click(function func_R(){
$(".in").attr("id","new-id");
});
</script>
<body>
<button id="old-id" class="in">Button A</button>
<button id="clear">Clear</button>
</body>
但我遇到的问题是,当我点击“按钮A”时,id会被更改,但当我再次单击“按钮A”时,func_P()会再次执行,而我打算调用func_Q。
答案 0 :(得分:2)
使用 .on 功能绑定(实时)点击。
$("#old-id").on('click', function func_P(e) {
//Some code
if (this.id == "old-id") {
this.id = "new-id";
console.log('old id clicked');
e.stopPropagation()
}
});
$(document).on('click', "#new-id", function func_Q() {
// some other code
console.log('new id clicked');
});
$("#clear").on('click', function func_R() {
$(".in").attr("id", "old-id");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="old-id" class="in">Button A</button>
<button id="clear">Clear</button>
如果你想清除id
,你应该改变:
$(".in").attr("id","new-id");
要强>
$(".in").attr("id", "old-id");