将html嵌入到javascript文件中

时间:2017-05-10 11:11:05

标签: javascript html

这是关闭和打开moda的脚本。当我在点击时触发事件时调用它。我想要一些HTML来在屏幕上呈现它。



<!-- Script for calling the modal -->
<script>
    $("body").delegate(".share.dash-button__feed", "click", function () {

        var thisID = $(this).attr('data-thdkls');
        $.post("/nodelike/nodelikes/dash_share/", {
                data: {
                    postid: thisID,
                }
            },
                /* The functionality when the "share" button is clicked */
            function () {
                //Load the modal
                var modal = document.getElementById('share-post');
                //Load the closing button
                var span = document.getElementsByClassName("close")[0];
                //Hide the modal if the "X" button is clicked
                span.onclick = function () {
                    modal.style.display = "none";
                }
                //Load and close the modal
                if (modal.style.display === 'none') {
                    modal.style.display = 'block';
                } else {
                    modal.style.display = 'none';
                }
                //Close the modal if you click outside the modal
                window.onclick = function (event) {
                    if (event.target == modal) {
                        modal.style.display = "none";
                    }
                }

            }
        );
    });
</script>
&#13;
&#13;
&#13;

我想在js文件中包含一些html和css。 我不确定该怎么做。

&#13;
&#13;
<!-- The HTML Modal for sharing a post by a user -->
<div id="share-post" class="modal" style="display: none;">
    <!-- Modal content -->
    <div class="modal-content">
        <span class="close">&times;</span>
        <p>Some random text....</p>
    </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

使用jQuery并通过使用和ID选择器选择它来获取html:

&#13;
&#13;
var html_content = $('#share-post')[0];
console.log(html_content);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="share-post" class="modal" style="display: none;">
    <!-- Modal content -->
    <div class="modal-content">
        <span class="close">&times;</span>
        <p>Some random text....</p>
    </div>
</div>
&#13;
&#13;
&#13;

您可以使用包含HTML的变量html_content。您可以在模态中使用此变量。