【问题标题】:How to set outerHTML with jQuery如何使用 jQuery 设置 outerHTML
【发布时间】:2012-01-05 11:36:33
【问题描述】:

我有一个用户控件。例如:

<div id="divItem">
some html
</div>

ajax 请求从服务器返回此 UC 的新 html。例如:

<div id="divItem">
    new html
</div>

我想用新的 html 替换旧的 html。我怎么能那样做。谢谢。

【问题讨论】:

  • 你试过jQuery Docs吗?
  • 如果包含开始和结束标记,则称为outerHTML。您要替换的部分是innerHTML

标签: javascript jquery asp.net ajax


【解决方案1】:

如果你还返回了 div divItem

$("#divItem").replaceWith("NEW HTML");

将新的 HTML 放在原处或替换 innerHTML,因为它们有相同的容器:

$("#divItem").html($("NEW HTML").html());

如果不返回 div divItem

只放新的html:

$("#divItem").html("NEW HTML");

【讨论】:

  • @roman 是的,因为如果我看到你的,我的不是最好的方法,我想提供一个完整的正确答案。但你得到了 +1。
  • 您应该清理这个答案,因为当 Jin 想要用新的替换旧的 html 时,它提供了两个答案。你应该用 .replaceWith 强调,你会得到我的 +1
【解决方案2】:

我猜replaceWith 是您搜索的内容。

$('#divItem').replaceWith(serverResponse);

【讨论】:

    【解决方案3】:

    可以使用.load() 将来自 AJAX 调用的数据放入 DOM 元素中。

    $('#divItem').load('somePage.html');
    

    【讨论】:

      【解决方案4】:

      如果您想用多个项目替换 1 个项目。你可以试试:

      var item_1 = $('<div>').text('item 1');
      var item_2 = $('<div>').text('item 2');
      var item_3 = $('<div>').text('item 3');
      
      // 1/.
      // dont' use this way because it's hard to read
      $('#divItem').prop('outerHTML', item_1.prop('outerHTML') + item_2.prop('outerHTML') + item_3.prop('outerHTML'));
      
      // 2/.
      // dont' use this way because it's same to the first's
      $('#divItem')[0].outerHTML = item_1.prop('outerHTML') + item_2.prop('outerHTML') + item_3.prop('outerHTML');
      
      // 3/.
      // if you use this way, how can we continue replace "#divItem" with "item_2"?
      var obj = $('#divItem').replaceWith(item_1);
      
      // "replaceWith" returns an object which was replaced with "item_1"
      // there is no way to continue with "item_2" and "item_3"
      // sure, if you DON'T want to write a new line
      item_1.after(item_2);
      
      // or
      item_2.insertAfter(item_1);
      
      // 4/.
      // if we write this, the result should be: "item 3item 2item 1"
      $('#divItem').after(item_1).after(item_2).after(item_3);
      
      // so, the correct **inline** solution should be:
      $('#divItem').after(item_3).after(item_2).after(item_1).remove();
      

      【讨论】:

        【解决方案5】:

        你只需要

        $('#divItem').html('new html');
        

        这只是替换了 div 的 innerHTML:http://api.jquery.com/html/

        【讨论】:

          猜你喜欢
          • 2021-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-12
          • 2016-08-20
          • 2015-06-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多