我正在尝试使用 li、ul、a 和 href 显示 HTML 页面中的 var fruits
(数组)的内容,用于特定单词(不是所有文本)。
例如,对于句子 I want a link here
我只想要单词 here
的链接,但我不知道该怎么做...
这是目前的代码:
<script>
// selects the div with an id of placeholder
var div = document.getElementById('placeholder');
// say that fruits contains all your data
var fruits = ['I want a link here','I want a link here','I want a link here','I want a link here','I want a link here'],
ul = document.createElement('ul'); // create an arbitrary ul element
// loop through the fruits array
for(var i in fruits) {
// create an arbitrary li element
var li = document.createElement('li'),
content = document.createTextNode(fruits[i]); // create a textnode to the document
var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = fruits[i];
li.appendChild(element); // append the created textnode above to the li element
ul.appendChild(li); // append the created li element above to the ul element
}
div.appendChild(ul); // finally the ul element to the div with an id of placeholder
</script>
最佳答案
一种可能的解决方案
var div = document.getElementById('placeholder');
// say that fruits contains all your data
var fruits = ['I want a link <a href="#">here</a>','I want a link here','I want a link here','I want a link here','I want a link here'],
ul = document.createElement('ul'); // create an arbitrary ul element
// loop through the fruits array
for(var i in fruits) {
// create an arbitrary li element
var li = document.createElement('li'),
content = document.createTextNode(fruits[i]); // create a textnode to the document
var link = "http://google.com";
var element = document.createElement("span");
element.innerHTML = fruits[i];
li.appendChild(element); // append the created textnode above to the li element
ul.appendChild(li); // append the created li element above to the ul element
}
div.appendChild(ul); // finally the ul element to the div with an id of placeholder
关于javascript - 使用 JavaScript 和 HTML5 在字符串的特定单词中 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36636921/