【问题标题】:jquery select by attribute name each this value pepend textjquery 按属性名称选择每个此值附加文本
【发布时间】:2014-08-31 09:50:28
【问题描述】:

通过某个属性名称选择元素,在本例中为“图标”:

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

然后在每个元素前面加上一个 &lt;span&gt; 与元素属性值的文本,
示例:

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

怎么做?

【问题讨论】:

  • 你试过什么???

标签: jquery jquery-selectors attributes each prepend


【解决方案1】:

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

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

DEMO

【讨论】:

    【解决方案2】:

    试试这个:

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

    Demo

    【讨论】:

      【解决方案3】:

      试试这个方法

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

      DEMO

      【讨论】:

        【解决方案4】:

        试试这个:

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

        【讨论】:

        • @downvoter 注意评论,这是一个新手错误,使用.before() 方法必须是.insertBefore()。已更新。
        猜你喜欢
        • 2014-12-26
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 2020-11-03
        • 2014-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多