简体   繁体   English

jQuery的更改按钮ID不起作用

[英]jQuery Changing button id doesn't work

I am writing a program where the signin button will be changed to sign out button when the user logged in. The code is as follow: 我正在编写一个程序,当用户登录时,登录按钮将更改为注销按钮。代码如下:

$("#signin").button().click(function(){
  $("#dialog-user").dialog("open");
});

$.post('php/in.php',function(data){
    $("#signin").attr('id','out');
});

$("#out").button().click(function(){
   alert("clicked out");
});

I have obmitted some code in between, but basically, when the user successfully signed in, the id of #signin button will be changed to #out. 我省略了两者之间的一些代码,但是基本上,当用户成功登录时,#signin按钮的ID将更改为#out。 However, when I click the new button with id #out, it doesn't show the alert("clicked out") that I specified. 但是,当我单击ID为#out的新按钮时,它不会显示我指定的警报(“被点击”)。 It still show the #dialog-user as if the button id is still #signin. 它仍然显示#dialog-user,好像按钮ID仍是#signin。

Please help me fix this. 请帮我解决这个问题。

You need to use event delegation As, #out doesn't exist when you are binding click event ie on page load 您需要使用事件委派方式,当您绑定点击事件(即页面加载)时, #out不存在

$(document).on('click',"#out",function(){
   alert("clicked out");
});

For such cases you would need to delegate the event to the static ancestor. 在这种情况下,您需要将事件委托给静态祖先。 As events are bound **to the elements and not to the attributes of an element . 因为事件是绑定到元素而不是元素属性

Try this approach.. 尝试这种方法。

$(document).on('click',"#out",function(){
   alert("clicked out");
});

Or 要么

$(signin static ancestor).on('click',function(e) {
      if(e.target.id === 'signin') {
          $("#dialog-user").dialog("open");  
      }
      else if(e.target.id === 'out') {
           alert("clicked out");
      }
});
$("#signin").button().click(function(){
  $("#dialog-user").dialog("open");
});

$.post('php/in.php',function(data){
    $("#signin").attr('id','out');
    $("#out").button().click(function(){
       alert("clicked out");
    });
});

In your example the id is changed after the event is tied, giving nothing to tie the event to. 在您的示例中,绑定事件后更改了id,因此没有将事件绑定到的内容。 Putting the out button click inside the post function ensures that when we get the data back from the server we change the id and THEN assign the event. 将out按钮放在post函数内部,可确保当我们从服务器取回数据时,我们更改ID,然后为该事件分配事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM