获取列表中的文本然后拆分它

时间:2017-02-26 15:52:50

标签: javascript jquery

我有一个像这样的标签列表

    <ul class="tagList">

        <li><a href="#">example1</a></li>
        <li><a href="#">example2</a></li>
        <li><a href="#">example3</a></li>
        <li><a href="#">example4</a></li>

    </ul>

现在我想在其中获取文本,然后像这样分割每个文本

example1 example2 example3 example4

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以先创建数组,然后join(' ')创建带空格的字符串。

&#13;
&#13;
var text = $('ul li a').map(function() {
  return $(this).text()
}).get().join(' ')

console.log(text)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tagList">
  <li><a href="#">example1</a></li>
  <li><a href="#">example2</a></li>
  <li><a href="#">example3</a></li>
  <li><a href="#">example4</a></li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Create separate file for css and paste this code:
        .tagList,li{
          display: inline;
        }

Now open html file and paste below lines:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="./CSS/style.css">
        <title> My home page</title>
      </head>
      <body>
        <ul class="tagList">

         <li><a href="#">example1</a></li>
         <li><a href="#">example2</a></li>
         <li><a href="#">example3</a></li>
         <li><a href="#">example4</a></li>

     </ul>
      </body>
    </html>

you can create separate CSS file or you can add within html file, depends on you. Hope you got me.