javascript 将html添加到div而不替换其中的当前内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14298989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add html to div without replacing the current content in it
提问by Hamada Badran
I'm trying to add dhtml to the div with the id upload_results. That should work without replacing the current content in the div.
我正在尝试将 dhtml 添加到 id 为 upload_results 的 div 中。这应该可以在不替换 div 中的当前内容的情况下工作。
The Code: (interesting part is at the bottom)
代码:(有趣的部分在底部)
<script language="JavaScript">
function do_show() {
$("#webcamContainer").fadeIn('');
}
webcam.set_hook( 'onComplete', 'my_completion_handler' );
function do_upload() {
upload to server
document.getElementById('upload_results').innerHTML = '<div>Uploading...</div>';
webcam.upload();
}
function my_completion_handler(msg) {
extract URL out of PHP output
if (msg.match(/(http\:\/\/\S+)/)) {
var image_url = RegExp.;
show JPEG image in page
$("#upload_results").fadeIn('');
//document.getElementById('upload_results').innerHTML = '<a target="_blank" href="'+image_url+'"><img style="border:#ccc 5px solid;" src="'+image_url+'" width="100px"></a>';// I think here should be something changed
$('#upload_results').append('<a target="_blank" href="'+image_url+'"><img style="border:#ccc 5px solid;" src="'+image_url+'" width="100px"></a>');
reset camera for another shot
webcam.reset();
}
else alert("PHP Error: " + msg);
}
</script>
<div id="upload_results" class="video_header" style="display:none;"></div><!--add data here , without replace current content in div-->
回答by Eru
check out: insertAdjacentHTML
method:
签出:insertAdjacentHTML
方法:
https://developer.mozilla.org/en-US/docs/DOM/element.insertAdjacentHTML
https://developer.mozilla.org/en-US/docs/DOM/element.insertAdjacentHTML
回答by Fabrício Matté
To append
content to the #upload_results
element:
为了append
内容的#upload_results
元素:
$('#upload_results').append('<a target="_blank" href="'+image_url+'"><img style="border:#ccc 5px solid;" src="'+image_url+'" width="100px"></a>');
You could also use .innerHTML += '[...]';
but that's usually considered bad practice as it overwrites existing DOM, trashing out existing listeners and data previously attached to the elements.
您也可以使用,.innerHTML += '[...]';
但这通常被认为是不好的做法,因为它会覆盖现有的 DOM,破坏现有的侦听器和先前附加到元素的数据。