html()
동일한 동작을하는 jQuery의 메서드 에 완전히 의존 할 수 있습니까 innerHTML
? innerHTML
와 jQuery의 html()
방법 사이에 차이점이 있습니까? 이 두 방법이 모두 동일하면 jQuery의 html()
방법을 대신 사용할 수 innerHTML
있습니까?
내 문제는 이미 디자인 된 페이지에서 작업 innerHTML
중이고 페이지에 테이블이 포함되어 있으며 JavaScript에서 속성을 사용하여 동적으로 채우는 것입니다.
응용 프로그램은 Firefox에서 제대로 작동 하지만 Internet Explorer 에서 오류가 발생합니다 unknown runtime exception
.. jQuery의 html()
방법을 사용했고 IE 의 오류가 사라졌습니다. 하지만 모든 브라우저에서 작동할지 확신 할 수 없으며 모든 innerHTML
속성을 jQuery의 html()
방법 으로 바꿀지 여부도 모르겠습니다 .
감사합니다.
답변
질문에 답하려면 :
.html()
.innerHTML
nodeTypes 등을 확인한 후 호출 합니다. 또한 먼저 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은 표준이 아니며 일부 브라우저에서는 작동하지 않을 수 있습니다. 나는 문제없이 모든 브라우저에서 html ()을 사용했습니다.
답변
“이 방법은 브라우저의 innerHTML 속성을 사용합니다.” -jQuery API
답변
요즘 의 일반적인 지원을.innerHTML
감안할 때 유일하게 효과적인 차이점은 제공하는 html에 태그가 있으면 모든 태그 에서 코드를 실행 한다는 .html()
것 입니다. , HTML5에서<script>
.innerHTML
에서는 그렇지 않습니다.
에서 JQuery와 문서 :
설계 상 HTML 문자열 (jQuery (), .append (), .after () 등)을 허용하는 모든 jQuery 생성자 또는 메서드는 잠재적으로 코드를 실행할 수 있습니다. 이는 스크립트 태그를 삽입하거나 코드를 실행하는 HTML 속성 (예 :)을 사용하여 발생할 수 있습니다
<img onload="">
. URL 쿼리 매개 변수, 쿠키 또는 양식 입력과 같은 신뢰할 수없는 소스에서 얻은 문자열을 삽입하는 데 이러한 방법을 사용하지 마십시오. 이렇게하면 XSS (교차 사이트 스크립팅) 취약성이 발생할 수 있습니다. 문서에 컨텐츠를 추가하기 전에 사용자 입력을 제거하거나 이스케이프하십시오.
참고 : .innerHTML
및 둘 다 .html()
js 다른 방법 (예 : onerror
속성)을 실행할 수 있습니다 .
답변
다음은 시작하는 데 도움이되는 몇 가지 코드입니다. .innerHTML의 동작을 수정할 수 있습니다. 완전한 .innerHTML shim을 만들 수도 있습니다. (추신 : .innerHTML 재정의는 Firefox에서도 작동하지만 Chrome에서는 작동하지 않습니다.
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)
