javascript 动态改变正文内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10555902/
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
Dynamically change body content
提问by Yustme
How do I dynamically change the body content of an html page when a link is clicked?
单击链接时如何动态更改 html 页面的正文内容?
So I have 3 html pages that looks like this:
所以我有 3 个 html 页面,如下所示:
<li><a id="homeContainer" href="#">Home</a></li>
<li><a id="testContainer" href='#'>test</a></li>
<li><a id="pageContainer" href="#">page</a></li>
My div:
我的div:
<div id='container'>
</div>
The javascript:
javascript:
$( document ).ready( function() {
$( '#testContainer' ).click( function() {
$( '#container' ).load('test.html');
});
This works fine if i make for all pages a separate function. But how can I make the javascript function taking a page in the load()
function instead of hardcoding it?
如果我为所有页面设置一个单独的功能,这很好用。但是如何让 javascript 函数在函数中占据一个页面load()
而不是对其进行硬编码?
[Edit]
[编辑]
I dropped my whole page with everything, html, javascript and css here: jsfiddle
我把我的整个页面都放在了这里,html,javascript 和 css: jsfiddle
回答by CaptainBli
I would suggest using jquery to change out your body with something else. Include the jquery code with:
我建议使用 jquery 用其他东西来改变你的身体。包含 jquery 代码:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
And then do something like this.
然后做这样的事情。
<a id='linkThatChangesTheWorld' href=''>Click Me</a>
<script>
$('#linkThatChangesTheWorld').click( function() {
$('body').html('I want my body this way.');
});
</script>
You can use functions like .prepend()
and .append()
if you just want to add some html to the body or if you have a specific div that you wish to change address it from its class:
您可以使用功能,如.prepend()
和.append()
,如果你只是想一些HTML补充人体或者如果你有一个特定的div,你希望从它的类别改变地址是:
If you have:
如果你有:
<div class='mychange'></div>
then use:
然后使用:
$('.mychange').append('<h2>Check it out</h2>');
Further, if you want to load from another page, you can use .get()
.
此外,如果您想从另一个页面加载,您可以使用.get()
.
$.get('myhtmlpage.html', function(data) {
//do something after getting the result
$('body').html($(data));
});
回答by ChristopheCVB
try :
尝试 :
HTML
HTML
<li><a id="homeContainer" href="home.html">Home</a></li>
<li><a id="testContainer" href='test.html'>test</a></li>
<li><a id="pageContainer" href="page.html">page</a></li>
Javascript
Javascript
$(document).ready(function()
{
$( 'li>a[id$="Container"]' ).click(function(event)
{
event.preventDefault();
var href = $(this).attr('href');
alert("Loading " + href)
$('#container').load(href);
return false;
});
});
Edit
编辑
Try out this JSFiddleusing JQuery
使用 JQuery试试这个JSFiddle