我可以在HTML中使用变量吗? [英] Can I use variables in HTML?

查看:811
本文介绍了我可以在HTML中使用变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有5个.html页面。每页都有相同的导航。有什么办法可以在某个地方设置一个包含我的导航代码的变量,然后在每个文档中引用该变量?

我想这样做,因为如果我想要编辑我的导航,我可以返回并编辑1个源文件(变量),而不是从每个文档进行编辑。

纯HTML(无JavaScript)无法自行载入另一个页面。但是,您可以使用PHP,SHTML或JavaScript来获取另一个页面并将其加载到页面中。



PHP



确保您的HTML文件已使用.php扩展名重命名。然后,您可以将以下行添加到要添加HTML文件的位置:

 <?php include('some_file_name.html ); ?> 

只要 some_file_name 存在,该页面将加载到PHP标签所在的位置。



SHTML



确保您的HTML文件已被重命名为.shtml扩展名。然后,您可以在要添加HTML文件的位置添加以下行:

 <! - #include virtual = some_file_name.html - > 

同样,只要 some_file_name 存在,该页面将在该页面加载。一定要注意间距,尤其是第二个破折号和之间,因为如果有空格,代码行将会中断。



JavaScript

使用JavaScript的好处在于您可以将HTML文件保存为.html文件。但是,需要更多代码才能加载包含的文件:

 < script src =jquery.js><<< ; /脚本> 
< script>
$(function(){
$(#includeThis)。load(some_file_name.html);
});
< / script>
...
< div id =includeThis>< / div>

这将创建一个函数,它将加载 some_file_name.html includeThis 所在的div标识。这包含更多开销,但您可以保留.html文件扩展名。


I have 5 .html pages. I have the same navigation for each page. Is there any way I can set a variable somewhere that contains my navigation code, and then reference that variable in each of my documents?

I want to do this because if I ever want to edit my navigation, I can just go back and edit 1 source (the variable), as opposed to editing from each document.

解决方案

Pure HTML (without JavaScript) cannot load in another page on it's own. However, you can use PHP, SHTML, or JavaScript to obtain another page and load it into the page.

PHP

Make sure that your HTML file has been renamed with the .php extension. Then you can add the following line where you want to add the HTML file:

<?php include('some_file_name.html'); ?>

As long as some_file_name exists, that page will load in where the PHP tag is.

SHTML

Make sure that your HTML file has been renamed with the .shtml extension. Then you can add the following line where you want to add the HTML file:

<!--#include virtual="some_file_name.html" -->

Again, as long as some_file_name exists, the page will load in the page at that. Be sure to watch for spacing, especially between the second dash and #, as the line of code will break if there is a space.

JavaScript

The plus side of using JavaScript is that you can keep your HTML file a .html file. However, more code is needed to load in the included file:

<script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#includeThis").load("some_file_name.html"); 
    });
    </script> 
...
<div id="includeThis"></div>

This will create a function that will load some_file_name.html where the div id of includeThis is located. This contains more overhead, but you can keep your .html file extension.

这篇关于我可以在HTML中使用变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆