简体   繁体   English

attr()不会更改ID-jQuery

[英]attr() doesn't change an id - jquery

I want to change id of div after every click on it. 我想在每次单击后更改div的ID。 But the .attr() change it only once, after first click. 但是.attr()第一次单击后只能更改一次。

$(function(){
  $('#m1').click(function(e){
    e.preventDefault();
    $('#m1').attr("id","m11");
    $('#m11').after('<div id="info_cont1">Hello m11 </div>');
  });

  $('#m11').click(function(e){
    e.preventDefault();
    $('#m11').attr("id","m1");
    $('#m1').after('<div id="info_cont1">Hello m1 </div>');
  });

});

Any ideas of such behaviour? 对这种行为有什么想法吗?

This is because you are binding the second .click function to the element #m11 which does not exist at that point, but the code runs at that early point. 这是因为您将第二个.click函数绑定到元素#m11,该元素当时不存在,但是代码在该早期点运行。 Therefore, use delegation: 因此,使用委派:

$(document).on('click', '#m11', function(event) {
    // code
});

SO the full code would be: 因此完整的代码将是:

$(function(){
    // you could actually also use .on() here :)
    $(document).on('click', '#m1', function(e) {
        e.preventDefault();
        $('#m1').attr("id","m11");
        $('#m11').after('<div id="info_cont1">Hello m11 </div>');
    });

    $(document).on('click', '#m11', function(e) {
        e.preventDefault();
        $('#m11').attr("id","m1");
        $('#m1').after('<div id="info_cont1">Hello m1 </div>');
    });

});

When you use the click method, it is being used at the very beginning of your scripts execution, when m11 doesn't exist. 当您使用click方法时,它在脚本执行的最开始即没有m11时就被使用。

If you simply want to toggle between id's m1 and m11 then do this: 如果您只想在id的m1m11之间切换,请执行以下操作:

$(function(){
  $('#m1').click(function(e){
    e.preventDefault();
    if($(this).attr('id') == 'm1'){
      $(this).attr("id","m11").after('<div id="info_cont1">Hello m11 </div>');
    }else{
      $(this).attr("id","m1").after('<div id="info_cont1">Hello m1 </div>');
    }
  });
});

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

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