代码之家  ›  专栏  ›  技术社区  ›  bsr

用jQuery脚本替换一个span,插入一段代码,其中包含原始文本

  •  0
  • bsr  · 技术社区  · 16 年前


    寻找一种干净的方法来删除一个span,并插入另一个代码块,其中包括原始内容。更具体地说,

    我所拥有的:

    <span class="error">ORIGINAL TEXT</span>
    

    (错误图标和格式与jQueryUI。遗憾的是,我无法更改原文,所以需要通过脚本来实现)

    <div class="ui-widget">
      <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;"> 
        <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"> </span>                
       <strong>ORIGINAL TEXT</strong></p>
      </div>
    </div>
    

    <span>

    2 回复  |  直到 16 年前
        1
  •  0
  •   sunetos    16 年前

    出于性能和组织方面的原因,我喜欢将标记保留在HTML中(而不是在javascript中构建大的HTML字符串),因此我通常会为这类事情创建隐藏的模板节点。您想要的jQuery函数是 replaceWith()

    HTML格式:

    <span class="error">ORIGINAL TEXT</span>
    <span class="error">ORIGINAL TEXT2</span>
    
    <div class="ui-widget" id="error-template" style="display:none;">
      <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
        <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"> </span>                
       <strong>ORIGINAL TEXT</strong></p>
      </div>
    </div>
    

    $(document).ready(function() {
        $('span.error').each(function(i,v) {
            var text = $(this).text();
            var newBlock = $('#error-template').clone().removeAttr('id').show();
            newBlock.find('strong:first').text(text);
            $(this).replaceWith(newBlock);
        });
    });
    

    See it in action at jsfiddle.

        2
  •  1
  •   Byron Sommardahl    16 年前

    <style>
        .ui-widget { display: inline; }
    </style>
    

    然后,需要用新的dom结构替换span:

    <script type="text/javascript">
        var originalText = $("span.error").text();
    
        $("span.error").replaceWith(
            $("<div>").attr("class", "ui-widget")
                .append($("<div>").attr("class", "ui-state-error ui-corner-all").attr("style", "padding: 0 .7em;")
                    .append($("p")
                        .append($("<span>").attr("class", "ui-icon ui-icon-alert").attr("style", "float: left; margin-right: .3em;"))
                    .append($("<strong>").text(originalText))
                )
            );
    
    </script>