单击后如何更改按钮的属性和ID?使用jQuery?

iCo*_*unk 2 jquery onclick

我试图让一个按钮动态更改其onclick和id属性。但是,为了准备就绪,我只能在第一次更改这些属性。

http://jsfiddle.net/WJTD5/1/

$("#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,然后单击
  • 如果不是,则保持不变

Asa*_*din 5

您是在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/