jquery按属性名称选择每个此值挂起文本

时间:2014-07-10 06:03:19

标签: jquery jquery-selectors attributes each prepend

按特定属性名称选择元素,在本例中为“icon”:

<a href="#" icon="one.png">link</a>
<a href="#" icon="two.png">link</a>
<a href="#" icon="three.png">link</a>

然后对每个元素,在<span>前加上元素属性值的文本,
例如:

<span>one.png</span><a href="#" icon="one.png">link</a>
<span>two.png</span><a href="#" icon="two.png">link</a>
<span>three.png</span><a href="#" icon="three.png">link</a>

怎么做?

4 个答案:

答案 0 :(得分:0)

尝试使用带有接收器功能的.before()来完成任务,

$('a[icon]').before(function(){
  return $("<span>", {text: $(this).attr('icon')});
})

DEMO

答案 1 :(得分:0)

试试这个:

$('a[icon]').each(function(){
   $(this).before('<span>'+$(this).attr('icon')+'</span>');
});

<强> Demo

答案 2 :(得分:0)

试试这种方式

$('a[icon]').each(function(){
   $(this).before('<span>'+$(this).attr('icon')+'</span>') 
});

DEMO

答案 3 :(得分:0)

试试这个:

$('a[icon]').each(function(){
   $('<span />', { text : this.getAttribute('icon') }).insertBefore(this);
});