我正在生成一个包含大量产品的页面,为此,我需要大量的ID,并且我使用服务器端(Python)进行了这样做,所以我发送每个产品自己的<div id='hello1'> test </div>
现在,因为用户将dinamycaly设置一个值并在浏览器中查看结果,我想生成另一个ID
,我发现btoa("hello1")
所以我生成了另一个ID
}
所以问题是,如何将btoa("hello1")
放入<div>
?
编辑:我想要生成的是另一个<div>
,而不是更新第一个。
<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>
如您所见,用户将设置一个值并动态查看。
这将在Python中使用:
<span id="{{base64.b64encode(str(produit["avt"]["fto"]))}}"></span>
但我可以使用Javascript完成,服务器将免费进行一半的操作!
答案 0 :(得分:57)
你的意思是这样吗?
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>'
。所以它会像这样出现:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
要创建元素并指定id
,我们可以使用document.createElement()
,然后使用appendChild()
。
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
<强>更新强>
如果您的脚本位于HTML文件中,则可以在元素上设置id
。
<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%明确。