如何使用javascript设置ID? [英] How to set ID using javascript?
问题描述
我正在生成一个包含大量产品的页面,为此,我需要大量的ID,我使用服务器端(Python),所以我发送每个产品自己的< ; div id ='hello1'>测试< / div>
I'm generating a page with lot of product, and for this, i need lot of ID, and i did it using a server side (Python) so i send for every product its own <div id='hello1'> test </div>
现在因为用户将dinamycaly设置一个值并在浏览器中查看结果,我想生成另一个 ID
,对此我发现 btoa(hello1)
所以我生成另一个 ID
Now because the user will dinamycaly set a value and see the result in the browser, i want to generate another ID
, to this i've found btoa("hello1")
so i generate another ID
所以问题是,如何把 btoa(hello1)
在< div>
?
So the question, how do i put btoa("hello1")
in <div>
?
编辑:我要生成的是另一个< ; div>
并且不更新第一个。
what i want to generate is another <div>
and not updating the first one.
<input id="{{str(product["avt"]["fto"])}}" > this will become <input id="12232" > because it is special to Tornado Template
<span>New price :</span>
<span id=btoa({{str(produit["avt"]["fto"])}})> This is where i use innerHTML </span>
如您所见,用户将设置一个值并动态查看。
as you can see, the users will put a value and see it dynamically.
这将在Python中使用:
This will work from Python using:
<span id="{{base64.b64encode(str(produit["avt"]["fto"]))}}"></span>
但如果可以使用Javascript完成,服务器将免费用于一半的操作!
but i if it can be done using Javascript, the server will be free for the half of the operations!
推荐答案
你的意思是这样吗?
var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);
为了进一步举例,说你想得到所有带有'abc'类的元素。我们可以使用 querySelectorAll()
来完成此任务:
HTML
<div class="abc"></div>
<div class="abc"></div>
JS
var abcElements = document.querySelectorAll('.abc');
// Set their ids
for (var i = 0; i < abcElements.length; i++)
abcElements[i].id = 'abc-' + i;
这将指定ID 'abc-< index number>'
到每个元素。所以它会这样:
This will assign the ID 'abc-<index number>'
to each element. So it would come out like this:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
创建元素并指定 id
我们可以使用 document.createElement()
然后 appendChild()
。
To create an element and assign an id
we can use document.createElement()
and then appendChild()
.
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
更新
如果您的脚本在HTML文件中,您可以在元素上设置 id
。
You can set the id
on your element like this if your script is in your HTML file.
<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">
<script type="text/javascript">
var s = document.getElementsByClassName('assign-me')[0];
s.id = btoa({{str(produit["avt"]["fto"])}});
</script>
您的要求仍然不是100%清楚。
Your requirements still aren't 100% clear though.
这篇关于如何使用javascript设置ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!