[英]Change the contents of a div using Javascript
单击锚标签时,我试图更改ID为#latestgames的div的内容。 该代码就在结束body标签之前
<script type="text/javascript">
$(function(){
$("a").click(function(){
if($(this).attr("id") == "web") {
$("#latestgames").html("<div>
</div>")
}
else if($(this).attr("id") == "app") {
$("#latestgames").html("<div>
</div>")
}
else if($(this).attr("id") == "uni") {
$("#latestgames").html("<div>
</div>")
}
else if($(this).attr("id") == "other") {
$("#latestgames").html("<div>
</div>")
}
});
});
</script>
如果相关,则每个div的内容将用ul填充。 锚标签列表如下
<li class="portfolio"><a id="web" href="javascript:void(0);">Web Development</a></li>
<li class="portfolio"><a id="app" href="javascript:void(0);">Web Development</a></li>
<li class="portfolio"><a id="uni" href="javascript:void(0);">Web Development</a></li>
<li class="portfolio"><a id="other" href="javascript:void(0);">Web Development</a></li>
在头上,我称以下
<script type='text/javascript' src='https://ajax.googleapis.com/ajax
/libs/jquery/1.7.2/jquery.min.js'></script>
对于我可能在做错的任何见解将不胜感激!
实际上,在javascript中,您无法在一行上打开字符串,然后在多行之后将其关闭。
你应该更换
$("#latestgames").html("<div>
</div>")
}
与
$("#latestgames").html("<div></div>")
}
问题是您的换行符会导致语句未终止(您应在控制台中查看是否有任何错误,这将为您提供一些线索):
$("#latestgames").html("<div>
</div>")
还简化您的代码:
$(function () {
$("a").click(function () {
var id = this.id; //get the id and cache it
var html = "";
switch (id) { //switch the value
case "web":
html = "somehtml";
break;
case "app":
html = "somehtml";
break;
case "uni":
html = "somehtml";
break;
case "other":
html = "somehtml";
break;
}
$("#latestgames").html(html); // set the html
});
});
多次调用$(this).attr("id")
也是不好的,也只能使用this.id
访问id,不要打扰jquery了...
我发现了一个更优雅的解决方案,它为编写div的内容提供了更大的灵活性。 我希望这可能对某人有用。 这恰好在结束body标签之前:
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#menu ul li a').click(function(){
$('#web').load('portfolio.html #' + $(this).attr('href'));
return false;
});
});
</script>
以下HTML进入了所需的网页:
<div>
<nav id="menu">
<ul class="portfolionav">
<li class="portfolionav"><a href="web">Web Development</a></li>
<li class="portfolionav"><a href="app">App Development</a></li>
<li class="portfolionav"><a href="uni">University/Early Work</a></li>
<li class="portfolionav"><a href="other">Other Stuff</a></li>
</ul>
</nav>
</div>
<div id="web">
<!--Any default HTML goes in here-->
</div>
Javascript引用了我创建并上传到服务器的HTML文件,该文件称为Portfolio.html。 该文件包含以下内容:
<div id="web">
<!--Any required HTML goes in here-->
</div>
<div id="app">
<!--Any required HTML goes in here-->
</div>
<div id="uni">
<!--Any required HTML goes in here-->
</div>
<div id="other">
<!--Any required HTML goes in here-->
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.