Add html to div without replacing the current content in it

痞子三分冷 提交于 2021-02-16 18:40:10

问题


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.

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.$1;
           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-->

回答1:


To append content to the #upload_results element:

$('#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.




回答2:


check out: insertAdjacentHTML method:

https://developer.mozilla.org/en-US/docs/DOM/element.insertAdjacentHTML



来源:https://stackoverflow.com/questions/14298989/add-html-to-div-without-replacing-the-current-content-in-it

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