2

Web ページ上のいくつかのリンクのタイトルを取得して、表に表示したいと考えています。ページ リンクは頻繁に変更されるため、テーブルを「動的」にしてリンク タイトルを正しく表示する方法がわかりません。

これは JavaScript で可能ですか?

4

1 に答える 1

4

次のようなhtmlを想定

  <div id="toc"></div>

  <a href="1" title="title of a1 link">a1</a> blah blah<br>
  <a href="2" title="title of a2 link">a2</a> blah blah<br>
  <a href="3" title="title of a3 link">a3</a> blah blah<br>

次のJavaScriptはあなたが望むことをします..

var links = document.getElementsByTagName('a'); // get all links
var toc = document.getElementById('toc'); // get the (table of contents) element where the titles will be inserted

for (var i = 0 ; i < links.length; i++)
{
  // for each link create a div
  newTitle = document.createElement('div');
  // which will hold the title of the link
  newTitle.innerHTML = links[i].title;

  // and then append it to the table of contents element..
  toc.appendChild( newTitle );
}
于 2010-05-10T09:59:00.567 に答える