如何在每个html页面中重用html代码?

GMs*_*soF 9 html css jquery

假设我的代码如下:

<!DOCTYPE HTML>
<html>
<head>
<style>
#overlay_form{
    position: absolute;
    border: 5px solid gray;
    padding: 10px;
    background: white;
    width: 270px;
    height: 190px;
}
#pop{
    display: block;
    border: 1px solid gray;
    width: 65px;
    text-align: center;
    padding: 6px;
    border-radius: 5px;
    text-decoration: none;
    margin: 0 auto;
}
</style>
<script src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    //open popup
    $("#pop").click(function(){
        $("#overlay_form").fadeIn(1000);
        positionPopup();
    });

    //close popup
    $("#close").click(function(){
        $("#overlay_form").fadeOut(500);
    });
});

//position the popup at the center of the page
function positionPopup(){
    if(!$("#overlay_form").is(':visible')){
        return;
    }
    $("#overlay_form").css({
        left: ($(window).width() - $('#overlay_form').width()) / 2,
        top: ($(window).width() - $('#overlay_form').width()) / 7,
        position:'absolute'
    });
}

//maintain the popup at center of the page when browser resized
$(window).bind('resize',positionPopup);

</script>
</head>
<body>

<a href="#" id="pop" >PopUp</a>
<br />
<form id="overlay_form" style="display:none">
<h2> Put your contents here..</h2>
<label>Username: </label><input type="text" name="username" /><br /><br />
<label>Password: </label><input type="text" name="password" /><br /><br />
<input type="button" value="Login" />
<a href="#" id="close" >Close</a>
</form>


</body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是一个弹出对话框示例.假设我想在我的所有网页(a.html,b.html,c.html等)中使用此对话框,使上面的代码可重用的最佳和最简单的方法是什么?因为我认为复制粘贴'overlay_form'到每个html页面是不合理的.

我仍处于Javascript的初级,因此为此创建一个jQuery插件对我来说太难了.这就是为什么我想寻求其他方法来做到这一点.谢谢.

Spo*_*key 14

您可以将代码放在不同的.html文件中并使用http://api.jquery.com/load/加载它.load()

$('#targetid').load('somewhere/a.html'); // loads the .html in the #targetid
Run Code Online (Sandbox Code Playgroud)

  • 这个a.html将如何被GoogleBot索引? (3认同)