简体   繁体   English

解析UL LI列表以逗号分隔的值

[英]Parsing a UL LI list to comma separated values

I need your help, 我需要你的帮助,

As it is right now, my function spits out my UL LI list as the below: 现在,我的函数如下所示弹出我的UL LI列表:

Coffee ,Tea ,Milk

I need to get it into the format of: 我需要将其转换为以下格式:

Coffee,Tea,Milk

Why does it add the extra spaces? 为什么要增加多余的空间?

function items_2_var() {

    var x = document.getElementById("list1").getElementsByTagName("li")

    var values = []

    for(var i=0;i < x.length; i++) {

        if (x[i].innerText.length) { values.push(x[i].innerText) }
    }

    alert(values.join(","))

}

HTML: HTML:

<div id="list1">
    <ul>
      <li>Coffee</li>
      <li>Tea</li>
      <li>Milk</li>
    </ul>
</div>

The only way I can reproduce the problem you describe is if you actually end up with an HTML rendered as so: 我可以重现您描述的问题的唯一方法是,如果最终得到的是这样呈现的HTML:

<div id="list1">
    <ul>
      <li>Coffee&nbsp;&nbsp;&nbsp;&nbsp;</li>
      <li>Tea&nbsp;&nbsp;</li>
      <li>Milk&nbsp;&nbsp;&nbsp;</li>
    </ul>
</div>

In that case, yo do see the space when you join the strings. 在这种情况下,当您连接琴弦时,确实会看到空格。 However, this is easy to fix by using the following instead: values.push((x[i].innerText.replace(/\\s/g,'')) 但是,通过使用以下代码可以轻松解决此问题: values.push((x[i].innerText.replace(/\\s/g,''))

Code: 码:

function items_2_var() {
    var x = document.getElementById("list1").getElementsByTagName("li");
    var values = [];
    for(var i=0;i < x.length; i++) {
        if (x[i].innerText.length) { values.push((x[i].innerText.replace(/\s/g,''))); }
    }
    alert(values.join(","));
}

Full demo here. 完整的演示在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM