56

我正在生成一个包含很多产品的页面,为此,我需要很多 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 完成,服务器将免费进行一半的操作!

4

1 回答 1

91

你的意思是这样吗?

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

更新

id如果您的脚本在您的 HTML 文件中,您可以像这样设置元素。

<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% 清楚。

于 2013-04-02T02:01:56.040 回答