使用 jQuery 加载到 Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6949638/
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
Load into Div using jQuery
提问by PeeHaa
I was looking for a lightweight way of loading external pages into a DIV onClick using jQuery.
我正在寻找一种使用 jQuery 将外部页面加载到 DIV onClick 的轻量级方法。
For example:
例如:
<a href="#" onclick="jQuery Load Function with unique ID 1">Load Page 1</a>
<a href="#" onclick="jQuery Load Function with unique ID 2">Load Page 2</a>
<a href="#" onclick="jQuery Load Function with unique ID 3">Load Page 3</a>
<a href="#" onclick="jQuery Load Function with unique ID 4">Load Page 4</a>
<div id="LoadMe">Where external page will load into</div>
Any help would be really appreciated,
任何帮助将非常感激,
Thanks!
谢谢!
回答by genesis
<a href="#" onclick="load(1);return false;">Load Page 1</a>
<a href="#" onclick="load(2);return false;">Load Page 2</a>
<a href="#" onclick="load(3);return false;">Load Page 3</a>
<a href="#" onclick="load(4);return false;">Load Page 4</a>
<div id="LoadMe">Where external page will load into</div>
<script>
function load(num){
$("#LoadMe").load('page'+num+'.php');
}
</script>
回答by PeeHaa
<a href="/page1">Load Page 1</a>
<a href="/page2">Load Page 2</a>
<a href="/page3">Load Page 3</a>
<a href="/page4">Load Page 4</a>
<div id="LoadMe">Where external page will load into</div>
$('a').click(function() {
$('#LoadMe').load($(this).attr('href'));
return false;
});
You might want to narrow the selector a
down though.
不过,您可能希望缩小选择器的范围a
。
回答by Ben Hull
Any reason you need onclick? If you can point your link to the page you want to fetch from the server, then jQuery's load method does exactly what you want. The simplest way I know of is:
你有什么理由需要点击吗?如果您可以将链接指向要从服务器获取的页面,那么 jQuery 的 load 方法正是您想要的。我知道的最简单的方法是:
<a href="loadThisPage1" class="pageFetcher">Load Page 1</a>
<a href="loadThisPage2" class="pageFetcher">Load Page 2</a>
<div id="LoadMe">Target div</div>
<script>
$(function(){
$('a.pageFetcher').click(function(){
$('#LoadMe').load($(this).attr('href'));
});
});
</script>
Using onclick attributes for events is very out-dated, and definitely at odds with the jQuery patterns for development.
对事件使用 onclick 属性非常过时,而且肯定与 jQuery 开发模式不一致。
回答by Louis Ferreira
Thanks for the question, made a small edit. Links within div wiki_links will fetch url and load content in wiki_c (as an alternative to the class for each link):
谢谢你的问题,做了一个小的编辑。div wiki_links 中的链接将获取 url 并加载 wiki_c 中的内容(作为每个链接的类的替代方案):
$("#wiki_links").on('click', 'a', function() {
$('#wiki_c').load($(this).attr('href'));
return false;
});