我需要能够拥有一个显示 div,并将内容从其他 div 加载到该单个 div 中,无需刷新
页面。假设我有以下结构:
Nav-div Display-div
-------------- -------------
| | | |
| >>item1<< | |content for |
| item2 | | item1 |
| item3 | | |
| | | |
| | | |
| | | |
-------------- --------------
jquery:
$("a.menu").click(function() {
var clicked = '#' + $(this).attr('title');
$('.toggle:not('+clicked+')').hide(1000);
$(clicked).show(1000);
});
HTML:
<div class="ShowClickedContent">
<!-- This Would be the display-div -->
</div>
<nav>
<a href="#" title="item1" class="menu">
<a href="#" title="item2" class="menu">
<a href="#" title="item3" class="menu">
</nav>
<div class="item1" style="display:none;">
<p> the content here will be loaded into the ShowClickedContent div </p>
</div>
<div class="item2" style="display:none;">
<p> the content here will be loaded into the div </p>
</div>
<div class="item3" style="display:none;">
<p> the content here will be loaded into the div </p>
</div>
到目前为止,我只能让 div 在自己的容器中显示,而不能在 showClickedContent
容器中显示。我该如何解决这个问题?
最佳答案
最简单的方法是使用 href
a
的属性保存 id
的元素目标div
元素。从那里您可以设置 .ShowClickedContent
的 HTML div 来匹配。试试这个:
$("a.menu").click(function(e) {
$('.ShowClickedContent').html($($(this).attr('href')).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ShowClickedContent"></div>
<nav>
<a href="#item1" class="menu">item1</a>
<a href="#item2" class="menu">item2</a>
<a href="#item3" class="menu">item3</a>
</nav>
<div id="item1" style="display: none;">
<p>the content here will be loaded into the ShowClickedContent div</p>
</div>
<div id="item2" style="display: none;">
<p>the content here will be loaded into the div #1</p>
</div>
<div id="item3" style="display: none;">
<p>the content here will be loaded into the div #2</p>
</div>
然而,将现有 HTML 复制到另一个元素只是为了使其可见(如果该内容已在 DOM 中),这似乎有点多余。为什么不根据需要隐藏/显示它,如下所示:
$("a.menu").click(function(e) {
$('.item').hide();
$($(this).attr('href')).show();
});
.item { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item1" class="item">
<p>the content here will be loaded into the ShowClickedContent div</p>
</div>
<div id="item2" class="item">
<p>the content here will be loaded into the div #2</p>
</div>
<div id="item3" class="item">
<p>the content here will be loaded into the div #2</p>
</div>
<nav>
<a href="#item1" class="menu">item1</a>
<a href="#item2" class="menu">item2</a>
<a href="#item3" class="menu">item3</a>
</nav>
关于jquery - 动态显示另一个div中div的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42856989/