Nice programing

JQuery html () 대 innerHTML

nicepro 2020. 10. 16. 08:05
반응형

JQuery html () 대 innerHTML


html()동일한 동작을하는 jQuery의 메서드 에 완전히 의존 할 수 있습니까 innerHTML? innerHTML와 jQuery의 html()방법에 차이가 있습니까? 이 두 방법이 모두 동일하면 jQuery의 html()방법을 대신 사용할 수 innerHTML있습니까?

내 문제는 이미 설계된 페이지에서 작업하고 있고 페이지에는 테이블이 포함되어 있으며 JavaScript에서 innerHTML속성을 사용하여 동적으로 채우고 있습니다.

응용 프로그램은 Firefox에서 제대로 작동 하지만 Internet Explorer 에서 오류가 발생합니다 unknown runtime exception.. jQuery의 html()방법을 사용했고 IE 의 오류가 사라졌습니다. 하지만 모든 브라우저에서 작동할지 확신 할 수 없으며 모든 innerHTML속성을 jQuery의 html()방법 으로 바꿀지 여부도 모르겠습니다 .

감사합니다.


질문에 답하려면 :

.html().innerHTMLnodeTypes 등을 확인한 후 호출 합니다. 또한 먼저 try/catch사용하려고 시도 하는 블록을 사용 innerHTML하고 실패하면 jQuery의 .empty()+append()


특히 "innerHTML처럼 수행 할 jquery html () 메서드에 완전히 의존 할 수 있습니까?"와 관련하여 내 대답은 아니요입니다!

인터넷 익스플로러 7 또는 8에서 이것을 실행하면 볼 수 있습니다.

jQuery는 문자열의 시작이 개행 인 <P> 태그 내에 중첩 된 <FORM> 태그를 포함하는 HTML을 설정할 때 잘못된 HTML을 생성합니다!

여기에는 몇 가지 테스트 사례가 있으며 실행시 주석은 충분히 자명해야합니다. 이것은 매우 모호하지만 무슨 일이 일어나고 있는지 이해하지 못하는 것은 약간 당황 스럽습니다. 버그 리포트를 제출하겠습니다.

<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>

이 기능에 대해 궁금해하는 경우, jQuery의 .html()같은 수행 목적 으로 기능 .innerHTML()하지만, 브라우저 간 호환성을 위해 그것은 또한 수행 확인합니다.

이러한 이유로, 항상 JQuery와의 사용 .html()대신에 .innerHTML()가능한.


innerHTML is not standard and may not work in some browsers. I have used html() in all browsers with no problem.


"This method uses the browser's innerHTML property." - jQuery API

http://api.jquery.com/html/


Given the general support of .innerHTML these days, the only effective difference now is that .html() will execute code in any <script> tags if there are any in the html you give it. .innerHTML, under HTML5, will not.

From the jQuery docs:

By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, <img onload="">). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.

Note: both .innerHTML and .html() can execute js other ways (e.g the onerror attribute).


Here is some code to get you started. You can modify the behavior of .innerHTML -- you could even create your own complete .innerHTML shim. (P.S.: redefining .innerHTML will also work in Firefox, but not Chrome -- they're working on it.)

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/

참고URL : https://stackoverflow.com/questions/3563107/jquery-html-vs-innerhtml

반응형