【问题标题】:How to get title attribute of element and insert it after element using jquery?如何使用jquery获取元素的title属性并将其插入到元素之后?
【发布时间】:2017-03-01 05:29:36
【问题描述】:

我有一个包含这样的列表元素的列表...

<li class="first leaf">
  <a href="/admin/store/orders/view" title="View and process the orders.">View orders</a>
</li>

我想获取 title 属性并将其作为 div 附加在 &lt;a&gt; 之后,就像这样...

<li class="first leaf">
  <a href="/admin/store/orders/view" title="View and process the orders.">View orders</a>
  <div>View and process the orders.</div>
</li>

到目前为止,我在这里......

(function ($) {    
  $('#block-menu-menu-admin-welcome li a').each(function () {
    $(this).append('<div>' + $(this).attr('title') + '</div>');
  });
})(jQuery);

但它不起作用。有人可以帮忙吗?

【问题讨论】:

标签: javascript jquery html attributes jquery-append


【解决方案1】:

JQuery .append() 将 html 插入选定元素,但您需要在选定元素之后插入 html。请改用.after()

$('#block-menu-menu-admin-welcome li a').each(function () {
    $(this).after('<div>' + $(this).attr('title') + '</div>');
});

$('a').each(function(){
    $(this).after('<div>' + this.title + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="first leaf">
    <a href="/admin/store/orders/view" title="View and process the orders.">View orders</a>
  </li>
</ul>

【讨论】:

  • 谢谢,但仍然无法正常工作。我用 console.log ('test') 打印了一条消息;它显示在控制台中,所以我知道 jquery 和 js 文件正在被注意到。
  • @Collins 代码在 sn-p 中工作。所以你的代码有问题。检查控制台是否有错误。
  • 控制台中没有错误。感谢您的帮助,我可以看到它可以工作,我得调试一下
【解决方案2】:

循环中的第一个 this 是对锚点的引用。您必须将其梳理到其父元素并附加到该元素。

$(this).parent().append('<div>' + $(this).attr('title') + '</div>');

【讨论】:

    【解决方案3】:

    这是给你的WORKING FIDDLE

    $(function(){
    
         $('.first').append($('.first a').attr('title'));
    
    });
    

    【讨论】:

      猜你喜欢
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2020-11-07
      • 2014-11-23
      • 1970-01-01
      • 2018-03-14
      相关资源
      最近更新 更多