JQuery html () vs. innerHTML

Czy mogę całkowicie polegać na metodzie jQuery html() zachowującej się identycznie jak innerHTML? Czy jest jakaś różnica między innerHTML A metodą jQuery html()? Jeśli te metody robią to samo, czy mogę użyć metody html() jQuery zamiast innerHTML?

Mój problem polega na tym, że pracuję na już zaprojektowanych stronach, strony zawierają tabele, a w JavaScript do ich dynamicznego wypełniania służy Właściwość innerHTML.

Aplikacja działa dobrze na Firefox ale Internet Explorer wyświetla błąd: unknown runtime exception. Użyłem metody html() jQuery i błąd IE zniknął. Ale nie jestem pewien, czy to będzie działać dla wszystkich przeglądarek i nie jestem pewien, czy zastąpić wszystkie właściwości innerHTML metodą html() jQuery.

Wielkie dzięki.

Author: Matthias Braun, 2010-08-25

7 answers

Aby odpowiedzieć na twoje pytanie:

.html() wywoła .innerHTML po sprawdzeniu nodetypów i takich tam. Używa również bloku try/catch, w którym najpierw próbuje użyć innerHTML, a jeśli to się nie powiedzie, z wdziękiem powróci do jQuery .empty() + append()

 97
Author: jAndy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-27 17:08:47

W szczególności w odniesieniu do "Czy mogę polegać całkowicie na metodzie jQuery html (), która będzie działać jak innerHTML" moja odpowiedź brzmi nie!

Uruchom to w internet explorer 7 lub 8 i zobaczysz.

JQuery generuje zły HTML, gdy ustawia HTML zawierający znacznik zagnieżdżony wewnątrz znacznika , gdzie początek ciągu znaków jest nową linią!

Jest tu kilka przypadków testowych, a komentarze podczas uruchamiania powinny być wystarczająco oczywiste. Jest to dość niejasne, ale nie rozumiejące to, co się dzieje, jest trochę niepokojące. Zgłoszę błąd.

<html>

    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>   

        <script>
            $(function() {

                // the following two blocks of HTML are identical except the P tag is outside the form in the first case
                var html1 = "<p><form id='form1'><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></form></p>";
                var html2 = "<form id='form1'><p><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></p></form>";

                // <FORM> tag nested within <P>
                RunTest("<FORM> tag nested within <P> tag", html1);                 // succeeds in Internet Explorer    
                RunTest("<FORM> tag nested within <P> tag with leading newline", "\n" + html1);     // fails with added new line in Internet Explorer


                // <P> tag nested within <HTML>
                RunTest("<P> tag nested within <FORM> tag", html2);                 // succeeds in Internet Explorer
                RunTest("<P> tag nested within <FORM> tag with leading newline", "\n" + html2);     // succeeds in Internet Explorer even with \n

            });

            function RunTest(testName, html) {

                // run with jQuery
                $("#placeholder").html(html);
                var jqueryDOM = $('#placeholder').html();
                var jqueryFormSerialize = $("#placeholder form").serialize();

                // run with innerHTML
                $("#placeholder")[0].innerHTML = html;

                var innerHTMLDOM = $('#placeholder').html();
                var innerHTMLFormSerialize = $("#placeholder form").serialize();

                var expectedSerializedValue = "field1=111&field2=222";

                alert(  'TEST NAME: ' + testName + '\n\n' +
                    'The HTML :\n"' + html + '"\n\n' +
                    'looks like this in the DOM when assigned with jQuery.html() :\n"' + jqueryDOM + '"\n\n' +
                    'and looks like this in the DOM when assigned with innerHTML :\n"' + innerHTMLDOM + '"\n\n' +

                    'We expect the form to serialize with jQuery.serialize() to be "' + expectedSerializedValue + '"\n\n' +

                    'When using jQuery to initially set the DOM the serialized value is :\n"' + jqueryFormSerialize + '\n' +
                    'When using innerHTML to initially set the DOM the serialized value is :\n"' + innerHTMLFormSerialize + '\n\n' +

                    'jQuery test : ' + (jqueryFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") + '\n' +
                    'InnerHTML test : ' + (innerHTMLFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") 

                    );
            }

        </script>
    </head>

    <div id="placeholder">
        This is #placeholder text will 
    </div>

</html>
 15
Author: Simon_Weaver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-12 19:55:10

InnerHTML nie jest standardem i może nie działać w niektórych przeglądarkach. Używałem html () we wszystkich przeglądarkach bez problemu.

 6
Author: Craig,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-25 06:09:49

Jeśli zastanawiasz się nad funkcjonalnością, to .html() jQuery wykonuje tę samą zamierzoną funkcjonalność jak .innerHTML(), ale sprawdza również zgodność między przeglądarkami.

Z tego powodu Zawsze używaj .html() jQuery zamiast .innerHTML() tam, gdzie to możliwe.

 6
Author: David Tang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-06 11:55:46

" ta metoda wykorzystuje Właściwość innerHTML przeglądarki."- jQuery API

Http://api.jquery.com/html/

 3
Author: codersarepeople,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-25 05:39:19

Biorąc pod uwagę ogólne wsparcie .innerHTML obecnie jedyną efektywną różnicą jest to, że .html() wykona kod w dowolnych znacznikach <script> , jeśli w podanym przez Ciebie kodzie html są jakieś. .innerHTML, pod HTML5 , nie będzie.

From The jQuery docs :

Według projektu, każdy konstruktor lub metoda jQuery, która akceptuje łańcuch HTML-jQuery (),.append (),after (), itp. - może wykonać kod. Może to nastąpić poprzez wstrzyknięcie znaczników skryptu lub użycie atrybutów HTML, które wykonują kod (na przykład <img onload="">). Nie używaj tych metod do wstawiania ciągów znaków uzyskanych z niezaufanych źródeł, takich jak parametry zapytań URL, pliki cookie lub dane wejściowe formularza. W ten sposób można wprowadzić luki w zabezpieczeniach cross-Site-scripting (XSS). Przed dodaniem zawartości do dokumentu usuń lub uniknij wprowadzania danych przez użytkownika.

Uwaga: zarówno .innerHTML jak i {[1] } mogą wykonywać js w inny sposób(np. atrybut onerror).

 1
Author: RedRiderX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-11 21:46:30

Oto kod na początek. Można modyfikować zachowanie .innerHTML-możesz nawet stworzyć własną całość .innerHTML shim. (P. S.: redefinicja .innerHTML będzie działał również w Firefoksie, ale nie w Chrome - pracują nad nim.)

if (/(msie|trident)/i.test(navigator.userAgent)) {
 var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
 var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
 Object.defineProperty(HTMLElement.prototype, "innerHTML", {
  get: function () {return innerhtml_get.call (this)},
  set: function(new_html) {
   var childNodes = this.childNodes
   for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
    this.removeChild (childNodes[0])
   }
   innerhtml_set.call (this, new_html)
  }
 })
}

var mydiv = document.createElement ('div')
mydiv.innerHTML = "test"
document.body.appendChild (mydiv)

document.body.innerHTML = ""
console.log (mydiv.innerHTML)

Http://jsfiddle.net/DLLbc/9/

 0
Author: Agamemnus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-21 07:30:58