我試圖在HTML頁面中使用li,ul,a和href顯示var fruits
(數組)的內容(並非所有文本) 。使用JavaScript和HTML5的字符串的特定字中的href
例如,對於句子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>
它的工作原理!非常感謝 – Gera