如何使用javascript为div标签提供唯一的ID [英] how to give a div tag a unique id using javascript

查看:147
本文介绍了如何使用javascript为div标签提供唯一的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用document.createElement('div')

I'm able to make a div tag using the document.createElement('div')

创建一个div标签但是我不知道如何给它一个唯一的id。

However i do not know how to give it a unique id.

任何人都可以帮我解决这个问题。

can anyone help me with this.

我知道如何使用innerHTML来做到这一点,但这非常麻烦。 (我听说这不是创建布局的好方法。)

I know how to do it using innerHTML however it very cumbersome. (I heard it not a good way of creating a layout.)

推荐答案

了解 unique 作为一个不能与标记中的任何其他ID混淆的ID,最简单的方法是获取本地时间戳。如图所示此处

Understanding unique as an ID that must not get mixed up with any other ID's in the markup, the easiest way to go is to get the local timestamp. As shown here:

let div = document.createElement("div");
// With old JS syntax
div.id = "div_" + new Date().getTime().toString();
// With ES6 Template Strings you can also write
div.id = `div_ ${new Date().getTime().toString()}`;

虽然使用 createElement 可能有点一个麻烦制造者,你应该使用一些JavaScript框架来解决你的小细节(如jQuery,Mootools,Dojo等)。

Though working with createElement can be a bit of a troublemaker, you should be using some JavaScript framework that solve the tiny little details for you (such as jQuery, Mootools, Dojo, etc.).

这篇关于如何使用javascript为div标签提供唯一的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆