【问题标题】:jQuery: get style attribute and append it to new <div>jQuery:获取样式属性并将其附加到新的 <div>
【发布时间】:2011-06-15 15:58:52
【问题描述】:

目前我有这样的图像(由 CKEditor 创建):

<img src="foo.jpg" style="float: left; margin-left: 20px;" alt="Image text">

我想在这张图片周围添加一个 div 并将 alt-tag 中的文本提取到一个 span 中。

$(document).ready(function () {
    $("#foo img").each(function() {
        $(this).wrap("<div class='imgtxt' />");
        $(this).after($("<span />").text($(this).attr("alt")));
     });
});

到目前为止,上帝!但我也想从 img 中获取样式属性并将其添加到新创建的 div 的 CSS 中。我怎样才能做到这一点?

【问题讨论】:

    标签: jquery css attr


    【解决方案1】:

    试试这个

    $(document).ready(function () {
        $("#foo img").each(function() {
            $(this).wrap("<div class='imgtxt' />");
            $('.imgtxt').attr('style', $(this).attr('style'));
            $(this).after($("<span />").text($(this).attr("alt")));
         });
    });
    

    【讨论】:

      【解决方案2】:

      你可以用这个:

      $(document).ready(function () {
          $("#foo img").each(function(index) {
              $(this).wrap("<div id='newdiv" + index + "'" class='imgtxt' />");
              $(this).after($("<span />").text($(this).attr("alt")));
              $("#newdiv" + index).attr('style', $(this).attr('style');
           });
      });
      

      您基本上是为每个 DIV 创建一个唯一 ID,然后每次都应用该样式

      【讨论】:

      • 这会将样式属性应用于相关的 DIV,此处的其他答案似乎使用类等将更新循环中的所有其他 DIVS 输出。
      【解决方案3】:
      $(this).closest('div.imgtxt').attr('style', $(this).attr('style'));
      

      closest() 将获取您刚刚创建的div。我还建议将代码更改为以下内容:

      $("#foo img").each(function() {
          var $this = $(this);
          $this.wrap("<div class='imgtxt' />");
          $this.after($("<span />").text($this.attr("alt")));
          // etc.
       });
      

      这样您就不会在每次调用 $(this) 时都查找/创建 jQuery 对象!

      【讨论】:

        【解决方案4】:

        将此行$(this).wrap("&lt;div class='imgtxt' /&gt;"); 替换为:

        $(this).wrap("<div class='imgtxt' style=\"" + $(this).attr("style") + "\" />");
        

        这会获取图像的样式属性并将其添加到新的div

        【讨论】:

          【解决方案5】:
          $('img').each(function() {
              var alt   = $(this).attr('alt'),
                  style = $(this).attr('style');
              $(this).after("<span>" + alt + "</span>")
                     .next('span')
                     .andSelf()
                     .wrapAll('<div class="imgtxt" style="'+style+'"></div>');
          });
          

          【讨论】:

            猜你喜欢
            • 2015-12-02
            • 2016-12-24
            • 1970-01-01
            • 2013-01-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-02-16
            相关资源
            最近更新 更多