首頁  >  問答  >  主體

javascript - id 是通过随机数生成的,使用jquery的removeAttr(‘id’),没有效果

    var id=Math.random();
    //var id="mm"
    $('body').html('<p id='+id+'>hha</p>');
    $('#'+id).removeAttr('id');
巴扎黑巴扎黑2735 天前516

全部回覆(6)我來回復

  • 阿神

    阿神2017-04-11 11:28:27

    因为生成的id中包含小数点,这个刚好与class选择器冲突了,不建议在id中包含小数点,这个需要这样改才能选择到这个元素

    $(('#'+id).replace('.', '\\.')).removeAttr('id');
    

    回覆
    0
  • 迷茫

    迷茫2017-04-11 11:28:27

    数字是不允许作为选择器使用的,你去控制台看报错

    还有就是你去控制台

    document.querySelector('#1')
    
    // Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#1' is not a valid selector.

    可以使用原生的另一个方法试下,

    document.getElementById('#1')
    
    //null

    你改写成 getElementById 试下

    回覆
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-11 11:28:27

    不要使用数字开头的 id 属性!在某些浏览器中可能出问题。
    console.log($('#'+id));//[] 没找到元素

    回覆
    0
  • PHPz

    PHPz2017-04-11 11:28:27

    嗯嗯,但是实际上追加到DOM上面的是字符型数字

    回覆
    0
  • 天蓬老师

    天蓬老师2017-04-11 11:28:27

    数字是不可以用作id的,你可以这样:var id = =''+d+Math.random();这样加一个字母

    回覆
    0
  • 黄舟

    黄舟2017-04-11 11:28:27

    生成随机字符串:
    
    randomString(6);
    
    function randomString(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';//可以自定义
        var maxPos = $chars.length;
        var pwd = '';
        for(i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }
    

    回覆
    0
  • 取消回覆