所以我想做几件事。我有一段 HTML,我希望默认显示在页面上(即第一次加载时)。
<div class="viewport">
<ul class="overview">
<li><img src="images/1.png" /></li>
<li><img src="images/2.png" /></li>
<li><img src="images/3.png" /></li>
<li><img src="images/4.png" /></li>
<li><img src="images/5.png" /></li>
<li><img src="images/6.png" /></li>
<li><img src="images/7.png" /></li>
</ul>
</div>
但是,在单击图标后,我希望随着 javascript 代码片段的更新而重新加载此部分。
图标的代码是:
<a href="#"><img src="images/2.png" id="icon#2"></a> |
<a href="#"><img src="images/3.png" id="icon#3"></a> |
<a href="#"><img src="images/4.png" id="icon#4"></a> |
更新的 JS 片段是:
var win_width = $(window).width();
var num_of_images = 2; // This should be changed to 3, when 3 is clicked, and 4 when 4 is clicked, etc.
因此它应该只在页面上重新加载“viewport”div...而不是整个页面。
想法?
最佳答案
$(function () {
var num_of_images = 2,
showAndHide;
$("img[id^=icon]").bind("click", function () {
num_of_images = parseInt(this.id.replace("icon#", ''), 10);
showAndHide(num_of_images);
});
(showAndHide = function (n) {
$("ul.overview").hide() // hide this while we "do work"
.children() // get children
.show() // show all children
.filter(":nth-child(" + n + ") ~ li") // get the next siblings of the nth child
.hide() // hide them
.end()
.end()
.show(); // show the parent list
})(num_of_images)
});
这是一个“悬而未决”的解决方案。我没有对此进行测试,如果它有效,我会感到惊讶。
编辑:好的,我测试并修复了一些问题,这似乎有效。
请注意,我将点击处理程序附加到那些 img
元素。因此,如果您不需要这些 anchor 标记,则不需要它们。
关于javascript - 如何在不刷新整个页面的情况下使用 jQuery 自动重新加载页面的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3737761/