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

jquery的replaceWith()和html()有什么区别?

  •  139
  • DMCS  · 技术社区  · 15 年前

    当HTML作为参数传入时,jquery的replaceWith()和html()函数有什么区别?

    5 回复  |  直到 7 年前
        1
  •  271
  •   Paolo Bergantino    15 年前

    采用此HTML代码:

    <div id="mydiv">Hello World</div>
    

    做:

    $('#mydiv').html('Aloha World');
    

    将导致:

    <div id="mydiv">Aloha World</div>
    

    做:

    $('#mydiv').replaceWith('Aloha World');
    

    将导致:

    Aloha World
    

    所以 html() 替换元素的内容,而 replaceWith() 替换实际元素。

        2
  •  30
  •   cgp    12 年前

    replaceWith()将替换当前元素,而html()只替换内容。

    请注意,replaceWith()实际上不会删除元素,只需将其从dom中移除并在集合中返回给您。

    彼得的一个例子: http://jsbin.com/ofirip/2

        3
  •  3
  •   Harsha    11 年前

    使用html()和replaceWith()jQuery函数有两种方法。

    <div id="test_id">
       <p>My Content</p>
    </div>
    

    1.)html()与replaceWith()。

    var html = $('#test_id p').html(); 将返回“我的内容”

    但是 var replaceWith = $('#test_id p').replaceWith(); 将返回的整个DOM对象 <p>My Content</p> .


    2.)html(“value”)与replaceWith(“value”)。

    $('#test_id p').html('<h1>H1 content</h1>'); 会给你以下的输出。

    <div id="test_id">
      <p><h1>H1 content</h1></p>
    </div>
    

    但是 $('#test_id p').replaceWith('<h1>H1 content</h1>'); 会给你以下的输出。

    <div id="test_id">
          <h1>H1 content</h1>
    </div>
    
        4
  •  2
  •   Benjamin Wootton    13 年前

    旧问题,但这可能对某人有所帮助。

    如果您的HTML无效,这些函数在Internet Explorer和Chrome/Firefox中的运行方式会有所不同。

    清除HTML,它们将按文档工作。

    (没有关闭我的 </center> 花了我一晚上的钱!)

        5
  •  1
  •   mistajolly    7 年前

    知道这一点也很有用 .empty().append() 也可以代替 .html() . 在下面显示的基准测试中,这是更快的,但仅当您需要多次调用此函数时。

    见: https://jsperf.com/jquery-html-vs-empty-append-test