javascript - id 是通过随机数生成的,使用jquery的removeAttr(‘id’),没有效果
巴扎黑
巴扎黑 2017-04-11 11:26:27
0
6
511
    var id=Math.random();
    //var id="mm"
    $('body').html('<p id='+id+'>hha</p>');
    $('#'+id).removeAttr('id');
巴扎黑
巴扎黑

Antworte allen(6)
阿神

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

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

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

还有就是你去控制台

document.querySelector('#1')

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

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

document.getElementById('#1')

//null

你改写成 getElementById 试下

伊谢尔伦

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

PHPzhong

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

Peter_Zhu

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

黄舟
生成随机字符串:

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;
}

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!