想要在元素中追加工具提示内容<li>


<div>
  <ul>
    <li>This is first point</li>
    <li>This is second point <a href="http://" title="This is more tooltip">More</a></li>
  </ul>
</div>

我想使用 jquery 在 li 元素中附加锚标签标题文本,以便获得没有超链接的纯文本。

例如,处理后li元素将是

<li>This is second point This is more tooltip</li>

这就是我的做法(代码中的注释来解释正在发生的事情(:

$('li').each(function() {  // loop through each li - you can change this selector to match your needs
  var li = $(this),
      anchors = li.find('a'); // in case there are multiple anchors?
  
  anchors.each(function() {
    var anchor = $(this),
        title = anchor.attr('title');
    
    if (typeof title !== typeof undefined && title !== false) { // do this if so only if the title attribute exists do you remove the anchor
      anchor.after(title);  // place the title after the link so it keeps it's place in the li (in case there is text after the link).  If you just want the text at the end of the li use li.append(title);
      anchor.detach();   // remove the anchor - move this to after the if statement if you want to remove the anchor and it's text regardless of whether or not it has a title.  If you want to keep the text in the anchor, just remove this line altogether
    }
  });
  
  // li.text(li.text()); // remove all other html within li (optional)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul>
    <li>This is first point</li>
    <li><strong>This is second point</strong> <a href="http://" title="This is more tooltip">More</a></li>
</ul>
</div>

这给了你想要的。 如果向元素添加 ID,请进行调整以使其更加简单。

var text = $("ul li:last a").attr("title");
$("ul li:last a").remove();
text = $("ul li:last").text() + text;
$("ul li:last").text(text);

JSFiddle

尝试使用标题:

<li id="yourElementId">example</li>

Javascript:

document.getElementById('yourElementId').title = 'your new title';

最新更新