innerHTML removing closing slash from image tag

丶灬走出姿态 提交于 2019-12-04 04:48:00

问题


This is very odd. Here is a quick test function:

function test_function(){
    code = '<img src="http://www.myimage.com/img.jpg" alt="image" />';
    alert(code);
    document.getElementById('test').innerHTML = code;
    alert(document.getElementById('test').innerHTML);
}

Running the code above will show /> in the first alert, but the second alert doesn't, it shows just >. So it looks like applying to .innerHTML strips out the forward slash. Any ideas how to stop this from happening? I need the forward slash for validation.


回答1:


The second alert just shows you what the browser uses as its internal representation of your image element. You don't need the slash for validation, as validation always is about your page's source, validators don't execute JavaScript that dynamically adds elements to the DOM.

In fact, most browsers handle XHTML internally just the same as HTML, not as an XML-representation of your document. Only when you send your XHTML document with MIME-type application/xhtml+xml, some browsers will render your page using the XML parser.

Also see Ian Hickson's article.



来源:https://stackoverflow.com/questions/4244434/innerhtml-removing-closing-slash-from-image-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!