问题描述
我需要能够只显示锚定的div,并且能够与该锚点共享链接。它不能按预期工作(尝试 bar1(空白)
bar2(空白)
链接)。加载包含锚 bar1
或 bar2
( www。 foo.bar/main.html#bar1
)无法正确处理css和jQuery,如果 bar1
(或 bar2
)从文件加载。另一方面,如果#foo元素附加为html字符串,则锚定链接似乎工作(例如
www.foo.bar/main.html#foo
)。要比较行为,请点击 foo(blank)
, bar1(blank)
, bar1
, bar2(blank)
和 bar2
链接, bar1 / code>和
bar2(空白)
链接未能显示 bar2
)div。显然它是与异步文件加载有关。是否有办法解决此问题?
I need to be able to show only anchored div and to be able to share the link with that anchor. It is not working as expected (try bar1 (blank)
bar2 (blank)
link). Loading main.html page (shown below) with an anchor bar1
or bar2
(www.foo.bar/main.html#bar1
) fails to properly handle css and jQuery if bar1
(or bar2
) is loaded from file. On the other hand if #foo element is appended as html string then anchored link seems to work (e.g. www.foo.bar/main.html#foo
). To compare behavior click foo (blank)
, bar1 (blank)
, bar1
, bar2 (blank)
and bar2
links, bar1 (blank)
and bar2 (blank)
links fail to show bar1
(or bar2
) div. Apparently it is related to asynchronous file loading. Is there a way to get around this issue?
main.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script>
$("<div>").load("bar1.html #bar1", function() {
$('body').append($(this).html());
});
$("<div>").load("bar2.html #bar2", function() {
$('body').append($(this).html());
});
$(function() {
$( 'body' ).append("<div id='foo' style='background-color:#8F8;'>FOO</div>");
});
</script>
<style>
div:not(:target) { display: none; }
div:target { display: block; }
</style>
</head>
<body>
<a href="main.html#foo" target="_blank">foo (blank)</a>
<a href="main.html#bar1" target="_blank">bar1 (blank)</a>
<a href="main.html#bar1">bar1</a>
<a href="main.html#bar2" target="_blank">bar2 (blank)</a>
<a href="main.html#bar2">bar2</a>
</body>
</html>
bar1.html :
<div id='bar1'>BAR1</div>
bar2.html :
<div id='bar2'>BAR2</div>
推荐答案
添加了文件计数器和函数,重置锚定代码。
Added a file counter and a function that decrements counter to reset the anchor tag.
main.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script>
var count = 2;
function onDataHandled() {
if (--count <= 0) {
var hash = window.location.hash;
window.location.hash = '';
window.location.hash = hash;
}
}
$.get('bar1.html', function (data) {
$('body').append(data);
onDataHandled();
});
$.get('bar2.html', function (data) {
$('body').append(data);
onDataHandled();
});
$(function() {
$( 'body' ).append("<div id='foo' style='background-color:#8F8;'>FOO</div>");
});
</script>
<style>
div:not(:target) { display: none; }
div:target { display: block; }
</style>
</head>
<body>
<a href="main.html#foo" target="_blank">foo (blank)</a>
<a href="main.html#bar1" target="_blank">bar1 (blank)</a>
<a href="main.html#bar1">bar1</a>
<a href="main.html#bar2" target="_blank">bar2 (blank)</a>
<a href="main.html#bar2">bar2</a>
</body>
</html>
这篇关于CSS +锚链接到从文件动态加载元素使用jQuery不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!