javascript - 使用 JavaScript 和 HTML5 在字符串的特定单词中 href

标签 javascript html css

我正在尝试使用 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>

FIDDLE

最佳答案

一种可能的解决方案

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

Fiddle

关于javascript - 使用 JavaScript 和 HTML5 在字符串的特定单词中 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36636921/

相关文章:

javascript - 数组作为 JavaScript 中 protected 对象属性

javascript - 如何从 RSS 获取图像 url?

javascript - 如何在控件容器中找到SAPUI5控件并将其显示在顶部部分?

javascript - 防止隐藏的 tr 破坏 td 宽度

php - Jquery slider 面板闪烁

javascript - 显示/隐藏按钮在 Mac 上不起作用

javascript - 如何使用 select 方法选择文本的一部分?

javascript - 用于导航用户的 Angular 三元运算符

python - 使用 Python 与包含动态列表的网页交互

javascript - CSS 旋转 Cube UI