如何根据用户输入生成修改后的超链接列表

时间:2015-08-07 21:21:42

标签: javascript html youtube

我尝试使用HTML或Javascript修改网址列表。我收集了一个嵌入任何YouTube视频的网站列表。它们看起来像这样:



<script type="text/javascript">
function changeText2(){
    var userInput = document.getElementById('userInput').value;
    var lnk = document.getElementById('lnk');
    lnk.href = "http://music-dump.com/id/" + userInput;
    lnk.innerHTML = lnk.href; 
}
</script>
&#13;
Type the youtube code and click Open! <a href="" id=lnk>link</a> <br>
<input type='text' id='userInput' value='' />
<input type='submit' onclick='changeText2()' value='Open'/>
&#13;
&#13;
&#13;

但这只会生成一个链接。我想要一个巨大的清单。有可能吗?

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

Type the youtube code and click Open! 
<div id="links">
</div>
<input type='text' id='userInput' value='' />
<input type='submit' onclick='changeText2()' value='Open'/>

和javascript:

var links = [
    "http://music-dump.com/id/00000",
    "http://youtube-id.com/download/00000",
    "http://example.com/v/00000"
];

function changeText2() {
    var userInput = document.getElementById('userInput').value;

    links.forEach(function(link) {
        link = link.replace("00000", userInput);
        var a = document.createElement("a");
        a.href = link;
        a.innerHTML = link;
        document.getElementById('links').appendChild(a);
    });
}

http://jsfiddle.net/u7hfuagw/2/

答案 1 :(得分:0)

您需要在列表中跟踪您的链接(在您的javascript文件中硬编码或通过XHR请求从服务检索)。然后,对于每个链接,在DOM中插入<a>标记。插入链接后,您只需要监听输入的值以更新href值;)

HTML文件:

<input type="text" id="userInput" placeholder="Start typing an ID...">
<ul id="links"></ul>

JS档案:

(function () {
  'use strict';

  // the "huge" list of links
  var linksCollection = [
    'http://music-dump.com/id/{id}',
    'http://youtube-id.com/download/{id}'
  ];

  init();

  function init() {
    var li, a;

    // for each link in the collection, we are going to create
    // a <a> element within a <li> element
    for (var i = 0; i < linksCollection.length; i++) {
      li = document.createElement('li');
      a = document.createElement('a');

      a.href = linksCollection[i].replace('{id}', 0);
      a.innerHTML = a.href;

      li.appendChild(a);
      document
        .getElementById('links')
        .appendChild(li);
    }

    document
      .getElementById('userInput')
      .addEventListener('keyup', handleInput);
  }

  function handleInput() {
    var inputElement = document.getElementById('userInput');
    var links = document.getElementById('links').childNodes;
    var aElement;

    for (var i = 0; i < links.length; i++) {
      aElement = links[i].getElementsByTagName('a')[0];
      aElement.href = linksCollection[i].replace('{id}', inputElement.value);
      aElement.innerHTML = aElement.href;
    }
  }
})();

链接到plunker:http://plnkr.co/edit/C1b6ccnpFrnNhDAsqxTF

PS:在上面的源代码中,<a>放置在<li>标记中,以获得更好的视觉呈现效果。您可以将<a>放在其他标签中,也可以为样式添加类名。例如:

li = document.createElement('li');
li.className = 'list-item';