我可以遍历一个p标签并更改为ul吗

Can I iterate through a p tag and change to an ul?

本文关键字:ul 标签 遍历 一个 我可以      更新时间:2023-09-26

我正在尝试创建一个脚本,该脚本遍历包含多个文本句子的段落,并在每个句子的开头和结尾插入li标记。这可能吗?

因此,将这段文字转为

<p>
   Give your work the edge with this pencil. Awesome design, and chunky gold finish. Get the look. 
</p>

进入这个无序列表

<p>
  <ul>
    <li>
      Give your work the edge with this pencil.
    </li> 
    <li>
      Awesome design, and chunky gold finish. 
    </li>
    <li>
      Get the look. 
    </li>
  </ul>
</p>
$('p').each(function() {
  var $par = $(this),
      theText = $par.text().split('. ');
  $par.text('');
  $.each(theText, function(i, item) {
    if ($.trim(item).length > 0)
      $par.append('<li>' + item + '</li>');
  });
});

未经测试,但你明白了。拆分,然后遍历数组,包装标签。

可以。首先你要做的就是Tokenize用"."将每个段落分隔成不同的句子,然后在其中添加li标记。。

要将内容从p更改为ul,您可以使用以下链接::

http://api.jquery.com/replaceWith/

要将单个段落标记成句子,可以使用以下方法:

http://www.tizag.com/javascriptT/javascript-string-split.php

您可以执行类似的操作

$.each($(".my-content").text().split("."), function(index,item){  
     $(".my-ul").append($("<li/>").text(item));
});