function initialize() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(-33.9, 151.2),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
setMarkers(map, beaches);
}
/**
* Data for the markers consisting of a name, a LatLng and a zIndex for
* the order in which these markers should display on top of each
* other.
*/
var beaches = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
function setMarkers(map, locations) {
// Add markers to the map
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var image = new google.maps.MarkerImage('images/beachflag.png',
// This marker is 20 pixels wide by 32 pixels tall.
new google.maps.Size(20, 32),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
new google.maps.Point(0, 32));
var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
shadow: shadow,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
}
}
На мой взгляд, лучшее решение использует jQuery:
a.html
:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html
:
<p>This is my include file</p>
Этот метод простое и чистое решение моей проблемы.
Документация jQuery .load()
здесь здесь .
На данный момент нет прямого решения HTML для задачи. Даже HTML Imports (который постоянно в черновике ) не будет делать этого, потому что Import! = Include и в любом случае потребуется какая-то магия JS. Недавно я написал скрипт VanillaJS , который предназначен для включения HTML в HTML без каких-либо осложнений.
Просто поместите в свой a.html
<link data-wi-src="b.html" />
<!-- ... and somewhere below is ref to the script ... -->
<script src="wm-html-include.js"> </script>
Это open-source
и может дать представление (надеюсь)
Большинство решений работают, но у них есть проблема с jquery:
Проблема заключается в следующем коде $(document).ready(function () { alert($("#includedContent").text()); }
: ничего не предупреждает, а не предупреждает о включении содержимого.
Я пишу ниже код , в моем решении вы можете получить доступ к включенному контенту в функцию $(document).ready
:
(Ключ загружается включенным содержимым синхронно).
index.htm:
<html>
<head>
<script src="jquery.js"></script>
<script>
(function ($) {
$.include = function (url) {
$.ajax({
url: url,
async: false,
success: function (result) {
document.write(result);
}
});
};
}(jQuery));
</script>
<script>
$(document).ready(function () {
alert($("#test").text());
});
</script>
</head>
<body>
<script>$.include("include.inc");</script>
</body>
</html>
include.inc:
<div id="test">
There is no issue between this solution and jquery.
</div>
Вы можете сделать это с помощью библиотеки JavaScript jQuery следующим образом:
HTML:
<div class="banner" title="banner.html"></div>
JS:
$(".banner").each(function(){
var inc=$(this);
$.get(inc.attr("title"), function(data){
inc.replaceWith(data);
});
});
Обратите внимание, что banner.html
должны находиться в том же домене, что и ваши другие страницы, в противном случае ваши веб-страницы откажутся от файла banner.html
из-за политик перекрестного источника ресурсов .
Также обратите внимание что если вы загрузите свой контент с помощью JavaScript, Google не сможет его индексировать, поэтому это не совсем хороший метод для SEO-причин.
Простое решение с php:
<?php
readfile("yourpath/yourpage.html");
?>
, используя библиотеку импорта jquery u need
, я рекомендую вам использовать php
<?php
echo"<html>
<body>";
?>
<?php
include "b.html";
?>
<?php
echo" </body>
</html>";
?>
b.html
<div>hi this is ur file :3<div>
Я знаю, что это очень старое сообщение, поэтому некоторые методы тогда не были доступны. Но это мой очень простой подход к этому (основанный на ответе Лоло).
Он опирается на атрибуты data- * HTML5 и поэтому является очень общим в том, что использует каждую функцию jQuery для каждой функции. class matching "load-html" и использует свой соответствующий атрибут «источник данных» для загрузки содержимого:
<div class="container-fluid">
<div class="load-html" id="NavigationMenu" data-source="header.html"></div>
<div class="load-html" id="MainBody" data-source="body.html"></div>
<div class="load-html" id="Footer" data-source="footer.html"></div>
</div>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$(".load-html").each(function () {
$(this).load(this.dataset.source);
});
});
</script>
Нет необходимости в скриптах.
<iframe src="/path/to/file.html" seamless></iframe>
Поскольку старые браузеры не поддерживают бесшовные, вы должны добавить некоторые css для исправления:
<iframe src="/path/to/file.html" seamless></iframe>
g2]
iframe[seamless] {
border: none;
}
Имейте в виду, что для браузеров, которые не поддерживают бесшовные, если вы нажмете ссылку в iframe, это сделает кадр отправится на этот URL-адрес, а не на все окно , Чтобы обойти это, чтобы все ссылки имели target="_parent"
, поддержка браузера «достаточно хороша».
На основе ответа https://stackoverflow.com/a/31837264/4360308 Я реализовал эту функцию с помощью Nodejs (+ express + cheerio) следующим образом:
HTML (index.html)
<div class="include" data-include="componentX" data-method="append"></div>
<div class="include" data-include="componentX" data-method="replace"></div>
JS
function includeComponents($) {
$('.include').each(function () {
var file = 'view/html/component/' + $(this).data('include') + '.html';
var dataComp = fs.readFileSync(file);
var htmlComp = dataComp.toString();
if ($(this).data('method') == "replace") {
$(this).replaceWith(htmlComp);
} else if ($(this).data('method') == "append") {
$(this).append(htmlComp);
}
})
}
function foo(){
fs.readFile('./view/html/index.html', function (err, data) {
if (err) throw err;
var html = data.toString();
var $ = cheerio.load(html);
includeComponents($);
...
}
}
append -> содержит содержимое в div
replace -> заменяет div
, вы можете легко добавить более поведение по той же схеме
После работы с содержимым html из некоторого файла необходимо включить: например, следующая строка будет содержать содержимое части__объекта.html в месте определения OBJECT.
...text before...
<OBJECT data="file_to_include.html">
Warning: file_to_include.html could not be included.
</OBJECT>
...text after...
Ссылка : http://www.w3.org/TR/WD-html40-970708/struct/includes.html#h-7.7.4
Вот отличная статья . Вы можете реализовать общую библиотеку и просто использовать ниже код для импорта любых файлов HTML в одной строке.
<head>
<link rel="import" href="warnings.html">
</head>
Вы также можете попробовать Google Polymer
Вы можете использовать polyfill из HTML Imports ( https://www.html5rocks.com/en/tutorials/webcomponents/imports/ ) или это упрощенное решение https: // github.com/dsheiko/html-import
Например, на странице вы импортируете блок HTML следующим образом:
<link rel="html-import" href="./some-path/block.html" >
Блок может иметь импорт своих own:
<link rel="html-import" href="./some-other-path/other-block.html" >
Импортер заменяет директиву загруженным HTML в значительной степени похожим на SSI
. Эти директивы будут подаваться автоматически, как только вы загрузите этот небольшой JavaScript:
<script async src="./src/html-import.js"></script>
Он будет обрабатывать импорт, когда DOM будет готов автоматически. Кроме того, он предоставляет API, который можно использовать для запуска вручную, для получения журналов и т. Д. Наслаждайтесь:)
PHP - это язык сценариев на уровне сервера. Он может делать много вещей, но одно популярное использование - включение HTML-документов внутри ваших страниц, во многом то же, что и SSI. Подобно SSI, это технология уровня сервера. Если вы не уверены, что у вас есть PHP-функции на вашем сайте, обратитесь к вашему провайдеру хостинга.
Вот простой PHP-скрипт, который вы можете использовать для включения фрагмента HTML на любую веб-страницу с поддержкой PHP:
Сохраните HTML для общих элементов вашего сайта, чтобы разделить файлы. Например, ваш раздел навигации может быть сохранен как navigation.html или navigation.php. Используйте следующий PHP-код для включения этого HTML на каждую страницу.
<?php require($DOCUMENT_ROOT . "navigation.php"); ?>
Используйте тот же код на каждой странице, которую вы хотите включить в файл. Обязательно измените имя файла с повышенным освещением на имя и путь к вашему включенному файлу.
Если вы используете какую-либо фреймворк, например django / bootle, они часто отправляют некоторый механизм шаблонов. Предположим, вы используете бутылку, а механизм шаблонов по умолчанию - SimpleTemplate Engine . Ниже приведен чистый html-файл
$ cat footer.tpl
<hr> <footer> <p>© stackoverflow, inc 2015</p> </footer>
. Вы можете включить footer.tpl в свой основной файл, например:
$ cat dashboard.tpl
%include footer
Кроме того, вы также можете передать параметр в ваш dashborard.tpl.
В w3.js включены такие работы:
<body>
<div w3-include-HTML="h1.html"></div>
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>
Ответ Атари (первый!) был слишком убедителен! Очень хорошо!
Но если вы хотите передать имя страницы, которая будет включена как параметр URL, этот пост имеет очень хорошее решение для использования в сочетании с:
http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
Таким образом, это будет примерно так:
Ваш URL:
www.yoursite.com/a.html?p=b.html
Теперь код a.html становится:
<html>
<head>
<script src="jquery.js"></script>
<script>
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
$(function(){
var pinc = GetURLParameter('p');
$("#includedContent").load(pinc);
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
Это сработало для меня очень хорошо! Я надеюсь, что помогли:)
Расширение ответа lolo сверху, вот немного больше автоматизации, если вам нужно включить много файлов:
<script>
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var file = 'views/' + $(this).data('include') + '.html';
$(this).load(file);
});
});
</script>
И затем включить что-то в html:
<div data-include="header"></div>
<div data-include="footer"></div>
Что будет включать в себя файлы views / header.html и views / footer.html
Бесстыдный штекер библиотеки, которую я написал, решил это.
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
Вышеуказанное будет содержать содержимое /path/to/include.html
и заменить его div
.
Чтобы вставить содержимое именованного файла:
<!--#include virtual="filename.htm"-->
Это помогло мне. Для добавления блока html-кода из b.html
в a.html
это должно перейти в тег head
в a.html
:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Затем в теге body сделан контейнер с уникальным id и блоком javascript для загрузки b.html
в контейнер следующим образом:
<div id="b-placeholder">
</div>
<script>
$(function(){
$("#b-placeholder").load("b.html");
});
</script>
В качестве альтернативы, если у вас есть доступ к файлу .htaccess на вашем сервере, вы можете добавить простую директиву, которая позволит интерпретировать php в файлах, заканчивающихся расширением .html.
RemoveHandler .html
AddType application/x-httpd-php .php .html
Теперь вы можете использовать простой PHP-скрипт для включения других файлов, таких как:
<?php include('b.html'); ?>
Ну, если все, что вам нужно сделать, это поместить текст из отдельного файла на вашу страницу (теги в тексте тоже будут работать), вы можете это сделать (ваши стили текста на главной странице - test.html
- все равно работать):
test.html
<html>
<body>
<p>Start</p>
<p>Beginning</p>
<div>
<script language="JavaScript" src="sample.js"></script>
</div>
<p>End</p>
</body>
</html>
sample.js
var data="Here is the imported text!";
document.write(data);
Вы всегда можете воссоздать теги HTML, которые вы хотите сами, в конце концов. Существует необходимость в серверных сценариях, чтобы захватить текст из другого файла, если вы не хотите делать что-то еще.
В любом случае, я начинаю использовать это для того, чтобы это сделать, если я обновляю описание, распространенное среди множества файлов HTML, мне нужно только обновить один файл, чтобы сделать это (файл .js
), а не каждый HTML-файл, содержащий текст.
Итак, в резюме вместо импортируя файл .html
, более простым решением является импорт файла .js
с содержимым файла .html
в переменной (и запись содержимого на экран, где вы вызываете скрипт).
Спасибо за вопрос.
html5rocks.com имеет очень хорошее руководство по этому материалу, и это может быть немного поздно, но я сам не знал, что это существовало. У w3schools также есть способ сделать это, используя свою новую библиотеку w3.js. Дело в том, что для этого требуется использование веб-сервера и объекта HTTPRequest. Вы не можете загружать их локально и тестировать на своем компьютере. Однако вы можете использовать полисы, указанные в ссылке html5rocks вверху, или следовать их руководству. С малой магией JS вы можете сделать что-то вроде этого:
var link = document.createElement('link');
if('import' in link){
//Run import code
link.setAttribute('rel','import');
link.setAttribute('href',importPath);
document.getElementsByTagName('head')[0].appendChild(link);
//Create a phantom element to append the import document text to
link = document.querySelector('link[rel="import"]');
var docText = document.createElement('div');
docText.innerHTML = link.import;
element.appendChild(docText.cloneNode(true));
} else {
//Imports aren't supported, so call polyfill
importPolyfill(importPath);
}
Это сделает ссылку (может измениться на желаемый элемент ссылки, если она уже установлена), установите импорт (если у вас уже нет это), а затем добавьте его. Затем он оттуда возьмет это и проанализирует файл в HTML, а затем добавит его к нужному элементу под div. Все это можно изменить в соответствии с вашими потребностями из добавляемого элемента к используемой вами ссылке. Я надеюсь, что это помогло, теперь это может быть неуместно, если появятся более быстрые и быстрые способы, не используя библиотеки и фреймворки, такие как jQuery или W3.js.
UPDATE: Это вызовет ошибку, говорящую, что локальный импорт были заблокированы политикой CORS. Может потребоваться доступ к глубокой сети, чтобы иметь возможность использовать это из-за свойств глубокого Интернета. (Нет практического использования)
Checkout HTML5 импортирует через учебник html5rocks и в polymer-project
Например:
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
Мое решение аналогично решению lolo выше. Однако я вставляю HTML-код через document.write JavaScript вместо использования jQuery:
a.html:
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
b.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
Причина, по которой я против использования jQuery заключается в том, что размер jQuery.js составляет ~ 90 КБ, и я хочу, чтобы количество загружаемых данных было как можно меньше.
Чтобы получить правильно экранированный JavaScript-файл без особых усилий, вы можете использовать следующую команду sed:
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
Или просто используйте следующий удобный скрипт bash, опубликованный как Gist на Github, который автоматизирует всю необходимую работу, конвертируя b.html
в b.js
: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
Кредиты на Грег Миншалл для улучшенной команды sed, которая также ускользает назад косые черты и одинарные кавычки, которые моя оригинальная команда sed не рассматривала.
Я пришел к этой теме, ища что-то подобное, но немного отличающееся от проблемы, заданной лоло. Я хотел создать HTML-страницу с алфавитным меню ссылок на другие страницы, и каждая из других страниц могла бы или не существовать, а порядок, в котором они были созданы, может быть не алфавитным (и даже не численным). Кроме того, как и Tafkadasoh, я не хотел раздувать веб-страницу с помощью jQuery. После исследования проблемы и экспериментов в течение нескольких часов, вот что сработало для меня, добавив соответствующие замечания:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/application/html; charset=iso-8859-1">
<meta name="Author" content="me">
<meta copyright="Copyright" content= "(C) 2013-present by me" />
<title>Menu</title>
<script type="text/javascript">
<!--
var F000, F001, F002, F003, F004, F005, F006, F007, F008, F009,
F010, F011, F012, F013, F014, F015, F016, F017, F018, F019;
var dat = new Array();
var form, script, write, str, tmp, dtno, indx, unde;
/*
The "F000" and similar variables need to exist/be-declared.
Each one will be associated with a different menu item,
so decide on how many items maximum you are likely to need,
when constructing that listing of them. Here, there are 20.
*/
function initialize()
{ window.name="Menu";
form = document.getElementById('MENU');
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = str.substr(tmp);
script = document.createElement('script');
script.type = 'text/javascript';
script.src = str + ".js";
form.appendChild(script);
}
/*
The for() loop constructs some <script> objects
and associates each one with a different simple file name,
starting with "000.js" and, here, going up to "019.js".
It won't matter which of those files exist or not.
However, for each menu item you want to display on this
page, you will need to ensure that its .js file does exist.
The short function below (inside HTML comment-block) is,
generically, what the content of each one of the .js files looks like:
<!--
function F000()
{ return ["Menu Item Name", "./URLofFile.htm", "Description string"];
}
-->
(Continuing the remarks in the main menu.htm file)
It happens that each call of the form.appendChild() function
will cause the specified .js script-file to be loaded at that time.
However, it takes a bit of time for the JavaScript in the file
to be fully integrated into the web page, so one thing that I tried,
but it didn't work, was to write an "onload" event handler.
The handler was apparently being called before the just-loaded
JavaScript had actually become accessible.
Note that the name of the function in the .js file is the same as one
of the the pre-defined variables like "F000". When I tried to access
that function without declaring the variable, attempting to use an
"onload" event handler, the JavaScript debugger claimed that the item
was "not available". This is not something that can be tested-for!
However, "undefined" IS something that CAN be tested-for. Simply
declaring them to exist automatically makes all of them "undefined".
When the system finishes integrating a just-loaded .js script file,
the appropriate variable, like "F000", will become something other
than "undefined". Thus it doesn't matter which .js files exist or
not, because we can simply test all the "F000"-type variables, and
ignore the ones that are "undefined". More on that later.
The line below specifies a delay of 2 seconds, before any attempt
is made to access the scripts that were loaded. That DOES give the
system enough time to fully integrate them into the web page.
(If you have a really long list of menu items, or expect the page
to be loaded by an old/slow computer, a longer delay may be needed.)
*/
window.setTimeout("BuildMenu();", 2000);
return;
}
//So here is the function that gets called after the 2-second delay
function BuildMenu()
{ dtno = 0; //index-counter for the "dat" array
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = "F" + str.substr(tmp);
tmp = eval(str);
if(tmp != unde) // "unde" is deliberately undefined, for this test
dat[dtno++] = eval(str + "()");
}
/*
The loop above simply tests each one of the "F000"-type variables, to
see if it is "undefined" or not. Any actually-defined variable holds
a short function (from the ".js" script-file as previously indicated).
We call the function to get some data for one menu item, and put that
data into an array named "dat".
Below, the array is sorted alphabetically (the default), and the
"dtno" variable lets us know exactly how many menu items we will
be working with. The loop that follows creates some "<span>" tags,
and the the "innerHTML" property of each one is set to become an
"anchor" or "<a>" tag, for a link to some other web page. A description
and a "<br />" tag gets included for each link. Finally, each new
<span> object is appended to the menu-page's "form" object, and thereby
ends up being inserted into the middle of the overall text on the page.
(For finer control of where you want to put text in a page, consider
placing something like this in the web page at an appropriate place,
as preparation:
<div id="InsertHere"></div>
You could then use document.getElementById("InsertHere") to get it into
a variable, for appending of <span> elements, the way a variable named
"form" was used in this example menu page.
Note: You don't have to specify the link in the same way I did
(the type of link specified here only works if JavaScript is enabled).
You are free to use the more-standard "<a>" tag with the "href"
property defined, if you wish. But whichever way you go,
you need to make sure that any pages being linked actually exist!
*/
dat.sort();
for(indx=0; indx<dtno; indx++)
{ write = document.createElement('span');
write.innerHTML = "<a onclick=\"window.open('" + dat[indx][1] +
"', 'Menu');\" style=\"color:#0000ff;" +
"text-decoration:underline;cursor:pointer;\">" +
dat[indx][0] + "</a> " + dat[indx][2] + "<br />";
form.appendChild(write);
}
return;
}
// -->
</script>
</head>
<body onload="initialize();" style="background-color:#a0a0a0; color:#000000;
font-family:sans-serif; font-size:11pt;">
<h2>
MENU
<noscript><br /><span style="color:#ff0000;">
Links here only work if<br />
your browser's JavaScript<br />
support is enabled.</span><br /></noscript></h2>
These are the menu items you currently have available:<br />
<br />
<form id="MENU" action="" onsubmit="return false;">
<!-- Yes, the <form> object starts out completely empty -->
</form>
Click any link, and enjoy it as much as you like.<br />
Then use your browser's BACK button to return to this Menu,<br />
so you can click a different link for a different thing.<br />
<br />
<br />
<small>This file (web page) Copyright (c) 2013-present by me</small>
</body>
</html>
Простая сторона сервера включает директиву для включения другого файла, найденного в той же папке, который выглядит следующим образом:
<!--#include virtual="a.html" -->