根据兄弟元素的属性预先添加HTML?

时间:2014-04-29 03:25:34

标签: javascript jquery html dom

我有这样的HTML:

<a attr="A" class="a1">Alabama</a>
<a attr="A" class="a1">Alaska</a>
<a attr="A" class="a1">Arkansas</a>

<a attr="C" class="a1">California</a>
<a attr="C" class="a1">Colorado</a>
<a attr="C" class="a1">Connecticut</a>

<a attr="N" class="a1">Nevada</a>
<a attr="N" class="a1">New york</a>
<a attr="N" class="a1">North Carolina</a>

如果内部文本具有相同的属性attr,请在其前面添加<b>标记。 那么如何使用javascript或jQuery获取HTML?

<b>A</b>
<a attr="A" class="a1">Alabama</a>
<a attr="A" class="a1">Alaska</a>
<a attr="A" class="a1">Arkansas</a>

<b>C</b>
<a attr="C" class="a1">California</a>
<a attr="C" class="a1">Colorado</a>
<a attr="C" class="a1">Connecticut</a>

<b>N</b>
<a attr="N" class="a1">Nevada</a>
<a attr="N" class="a1">New york</a>
<a attr="N" class="a1">North Carolina</a>

1 个答案:

答案 0 :(得分:2)

var last = '';
$('.a1').each(function () {
    if ($(this).attr('attr') != last) {
        $(this).before('<b>' + $(this).attr('attr') + '</b>')
        last = $(this).attr('attr');
    }
})

<强> jsFiddle example