在列表中创建链接

时间:2016-04-03 22:28:22

标签: javascript html dom

我有一个看起来像这样的列表

<li class="list">text1</li>
<li class="list">text2</li>
<li class="list">text3</li>

并希望使用JavaScript

将文本转换为链接
<li class="list><a href="#text1">text1</a></li>
<li class="list><a href="#text1">text1</a></li>
<li class="list><a href="#text1">text1</a></li>

我已经这样做了,但不知道下一步怎么办?

var link1 = document.createElement("a");
link.href = "#text1"

是否可以制作循环或类似的东西,这样我就不必为所有三个链接编写相同的代码?

2 个答案:

答案 0 :(得分:2)

是的,首先你需要找到所有列表类标签并循环遍历它们。

var lists = document.getElementsByClassName("list");
for(var i=0; i<lists.length; i++) {

接下来找到当前列表元素的文本,将其存储在变量中,然后清除元素的文本。

var text = lists[i].textContent;
lists[i].textContent = "";

第三,创建a元素,并使a元素的textContent成为当前列表和href的文本,当前文本加上#符号。

var a = document.createElement("a");
a.href = "#"+text;
a.textContent = text;

最后将a附加到当前列表元素。

lists[i].appendChild(a);

var lists = document.getElementsByClassName("list");
for(var i=0; i<lists.length; i++) {
  var text = lists[i].textContent;
  lists[i].textContent = "";
  var a = document.createElement("a");
  a.href = "#"+text;
  a.textContent = text;
  lists[i].appendChild(a);
}
<li class="list">text1</li>
<li class="list">text2</li>
<li class="list">text3</li>

`

答案 1 :(得分:1)

迭代列表元素,将锚点HTML添加为文本替换:

wildcards = ['?', '#', '&'] #user has entered wildcards in this order
n = len(wildcards)
list = itertools.product('abc123',repeat=n) #creates a cartesian product of every combination of letters and numbers (only using abc123 to be more manageable for now. 
print(list)
for x in list: #going to iterate through the list
    iter = 0
    while iter < n: #iterating through an individual object in the list
        if wildcards[iter] == '#': #if that index should be a number but isn't, we delete that object from the list
            if x[iter] != string.digits:
                del list[x]
        elif wildcards[iter] == '&': #if it should be a letter and isn't we delete the object
            if x[iter] != string.ascii_lowercase:
                del list[x]
        iter = iter+1
print(list) #print the new list

DEMO