如何获取元素的title属性并使用jquery在元素后面插入?

时间:2016-10-19 14:05:53

标签: javascript jquery html attributes jquery-append

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

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

我想获取title属性并将其作为div添加到<a>之后......

<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);

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

3 个答案:

答案 0 :(得分:2)

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

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

&#13;
&#13;
$('a').each(function(){
    $(this).after('<div>' + this.title + '</div>');
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

你的循环中的第一个是对锚点的引用。你必须将其梳理到其父元素并追加到它。

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

答案 2 :(得分:0)

以下是WORKING FIDDLE

$(function(){

     $('.first').append($('.first a').attr('title'));

});
相关问题