Javascript Jquery 加载外部 HTML 的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11134701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Load Part of External HTML
提问by LmC
Basicily i have a index.html shown below..
基本上我有一个 index.html 如下所示..
<html>
<head>
<title>UI Test: Main Menu</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="general.js"></script>
</head>
<body>
<input type="button" value="Details" onclick="javascript:$('#mainContainer').load('loadpage.html #name1div *');"/><br>
<div id="mainContainer">
</div>
The loadpage.html cotaints
loadpage.html cotaints
<div id="nav1div><h3>1 DIV </h3> </div>
<div id="nav2div><h3>2 DIV </h3> </div>
<div id="nav3div><h3>3 DIV </h3> </div>
<div id="nav4div><h3>4 DIV </h3> </div>
And my objective is to basicly load 1 of the divs at a time in to the main container, i know the load function can load the full page at once but this is NOT what i need to do.
我的目标是基本上一次将 1 个 div 加载到主容器中,我知道加载功能可以一次加载整个页面,但这不是我需要做的。
Had a few look at similar questions but cant seem to resolve this..
看过一些类似的问题,但似乎无法解决这个问题..
All help is appreciated thanks guys!
感谢大家的帮助!
回答by GShenanigan
The jQuery .load()
function allows you to specify a portion of a page to load, rather than just the whole document.
jQuery.load()
函数允许您指定要加载的页面的一部分,而不仅仅是整个文档。
e.g.
例如
$('#mainContainer').load('loadpage.html #nav1div');
Check out the jQuery load()
documentationparticularly where it regards “Loading Page Fragments”.
查看jQueryload()
文档,特别是有关“加载页面片段”的内容。
回答by Cranio
To load DIVs one after another, define a counter
要一个接一个地加载 DIV,请定义一个计数器
var curDiv = 1; // current Div
somewhere at the beginning (better to define a $(document).ready()
function to initialize it).
Define this function:
在开始的某个地方(最好定义一个$(document).ready()
函数来初始化它)。定义这个函数:
function loadThing()
{
if (curDiv<5) $('#mainContainer').load('loadpage.html #nav' + (curDiv++) + 'div');
}
Define the click event like:
定义点击事件,如:
$("input#getdiv").click(loadThing);
and you button like:
然后你按下按钮:
<input id="getdiv" type="button" value="Details" />
With every click you should get first div, second, and so on.
每次点击你应该得到第一个 div,第二个,依此类推。
With this approach you separate JS from HTML, which is always good.
通过这种方法,您可以将 JS 与 HTML 分开,这总是好的。
回答by Dan Smith
jQuery load
can easily load page fragments, like so
jQueryload
可以轻松加载页面片段,就像这样
$('#mainContainer').load('loadpage.html #nav1div');