【问题标题】:How to use the li-name as link in the li-item如何使用 li-name 作为 li-item 中的链接
【发布时间】:2020-03-30 08:22:37
【问题描述】:

嘿,

我有一个 javascript 函数来获取当前页面上的所有 '' 项目。这可以正常工作,但我想使用输出名称作为每个 li 项目的链接。这里举个例子:

其中一个 li 项目的名称为:'Scalder'。它看起来像这样:

<ul>
  <li>Scalder</li>
  <li>other-item</li>
  <li>other-item</li>
  <li>other-item</li>
</ul>

我想得到这样的结果:

<ul>
  <li id='Scalder'>Scalder</li>
  <li id='other-item'>other-item</li>
  <li id='other-item'>other-item</li>
  <li id='other-item'>other-item</li>
</ul>

每个项目还必须设置li-item的链接。

我当前的构建代码是:

var mainEl = document.getElementsByTagName("main"),
      //Because we only have one main tag, from the previous
      //collection we chose the first elemnt
      //From that element we create a collection with all the h2 inside
      headingsEls = mainEl[0].getElementsByTagName("output"),
      //collection of elements with "aside" tag
      asideEl = document.getElementsByTagName("aside"),
      //We create the ul that wil hold the list
      ulEl = document.createElement("ul")

    //Go throw the h2 collection and for each element we create a new li element,
    //we pass to it the text content and we put it on the ul
    for( var i = 0; i < headingsEls.length; i++ ) {

        var liEl = document.createElement("li")

        liEl.textContent = headingsEls[i].textContent
        ulEl.appendChild(liEl)
    }

    //the new ul with the list is appended!
    asideEl[0].appendChild(ulEl)

希望我清楚我的愿望。祝你有美好的一天!

【问题讨论】:

  • 所以你想设置每个liid 来匹配它的文本?请注意,您可能很容易在此处出现重复,并且文本中的任何空格都将意味着 id 无效。不过,我会问你为什么觉得有必要这样做,因为在运行时设置 id 是一种小代码气味。

标签: javascript jquery html hyperlink


【解决方案1】:

使用 jQuery

对每个&lt;li&gt; 元素使用$(this).attr('id',$(this).text());

$('ul li').each(function() {
  $(this).attr('id',$(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>Scalder</li>
  <li>other-item1</li>
  <li>other-item2</li>
  <li>other-item3</li>
</ul>

使用 JavaScript

var elem = document.querySelectorAll('ul li');
for(var i=0; i<elem.length; i++){
  elem[i].setAttribute('id',elem[i].innerText);
}
<ul>
  <li>Scalder</li>
  <li>other-item1</li>
  <li>other-item2</li>
  <li>other-item3</li>
</ul>

【讨论】:

    【解决方案2】:

    编写一个根据输出返回 html 的函数


    代码

    function convertlistTolinks(){
        let html = "";  
        html +=`<ul>`
        for(var i = 0; i < headingsEls.length; i++ ){
          html +=`<li id=`${headingsEls[i].element}`><a>`${headingsEls[i].element}`</a</li>`    
        }
        html +=`</ul>`;
       //appending the dynamic list to the parent element in the dom
        document.getElementById("parentElement").appendChild(html)
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 2015-12-23
      • 2013-03-05
      • 2014-07-27
      • 1970-01-01
      相关资源
      最近更新 更多