0

嘿,我有这段代码,但它没有按我想要的那样工作

function showcode() {
    if ($('#sampleeditor').text() != '') {//check if the div is not empty => not working
        var orgcontent = document.getElementById('sampleeditor').innerHTML;//get the content of the div
        var copiedcontent = document.getElementById('contentcode').innerHTML = orgcontent;//place the content in the target div || the issue here is that the content is shown as it is|| I want it to be a text of the code
    } else {
        document.getElementById('contentcode').innerHTML = "Nothing to show";//if the original div is empty show this text
    }
    $("#Showcode").modal('show');// the modal where the contentcode is placed.
}

基本上我希望代码获取 div(sampleeditor) 的内容并将它们作为文本显示在 modal(showcode) 内的另一个 div (contentcode) 中。

此代码按原样复制内容。例如。如果我在第一个 div 中有一个图像,它会在另一个 div 中显示为图像。我希望它是这样的div class="divimage" id="WNI4022"><img src="empty.jpg" width="100px" height="100px"></div>

4

1 回答 1

2

您正在寻找的方法不是innerHTML——这只会给你元素中的内容......替换outerHTML它会给你元素的实际源代码——在这种情况下是orgcontent变量


我已经注意到问题出在哪里

function escapeHtml(text) {
  var map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };

  return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
// The above is a function to change the special characters so they can show up in the <code> tag

function showcode() {
    if ($('#sampleeditor').text() != '') {//check if the div is not empty => not working
        var orgcontent = document.getElementById('sampleeditor').outerHTML;//get the content of the div
        var copiedcontent = document.getElementById('contentcode').innerHTML = orgcontent;//place the content in the target div || the issue here is that the content is shown as it is|| I want it to be a text of the code
        document.getElementById('formatted-contentcode').innerHTML = escapeHtml(orgcontent);
        // The above formatted-contentcode will have the escaped characters
    } else {
        document.getElementById('contentcode').innerHTML = "Nothing to show";//if the original div is empty show this text
    }
}
$(document).ready(function(){
  showcode();
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<div id="sampleeditor">This will be shown in the other div</div><br/>
<!-- If you want to put actual source code in a div, you have to wrap them in code tags
Then escape "<" as "&lt;" and ">" as "&gt;"
-->
<div id="contentcode">Another thing</div><br/>
<!--  Notice the difference  
The one below has been passed to the `escapeHtml()` function -->
<div id="formatted-contentcode">Another thing</div>

为了让您放置实际的源代码,它们必须在<code>标签中,并且您必须转义特殊字符......该escapeHtml()函数完成了这项工作。

另一种方法是将源代码放在将显示为实际代码的文本区域或输入元素中。

于 2020-06-11T19:06:12.410 回答