gpt4 book ai didi

javascript - 脚本不适用于包含的 html

转载 作者:行者123 更新时间:2023-11-28 15:51:35 25 4
gpt4 key购买 nike

我正在关注这个 http://www.w3schools.com/howto/howto_html_include.asp包括 html

所以有一个 html 文件,即 sidebar.html,它包含在各种 html 文件中。

我想在 sidebar.html 中保留如下共享代码

<a id="fbshare" href="" target="_blank">  
<img src="https://example1.com/facebook.png" alt="Facebook" />
</a>

但是因为有200多页所以我想根据那个html页面的url放href。

所以我在我的 main.js 中使用这个脚本

jQuery(document).ready(function() {
var share_url = document.URL;

document.getElementById( "fbshare" ).href = 'http://www.facebook.com/sharer.php?u=' + share_url;
});

这是我的一个 html 页面的代码

<!DOCTYPE html>
<head>
</head>
<body>
<header w3-include-html="header.html"></header>

<main>

<div id="main-slider" class="carousel slide carousel-fade" data-ride="carousel">
<div class="container">
<aside class="col-md-3 col-sm-4" w3-include-html="sidebar.html"></aside>

</div>
</div>

</main>
<footer w3-include-html="footer.html"></footer>


<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript" src="js/owl.carousel.js"></script>
<script type="text/javascript" src="js/w3data.js"></script>



<script>
w3IncludeHTML();
</script>
<script type="text/javascript" src="js/main.js" defer></script>
</body>
</html>

但是写 href 的脚本不工作..

我卡在这上面了。请帮忙

最佳答案

使用 window.location.href 获取当前页面的 url。然后你可以为你的元素设置 href 属性。

试试这个:

jQuery(document).ready(function() {
var share_url = window.location.href;

document.getElementById( "fbshare" ).setAttribute('href','http://www.facebook.com/sharer.php?u=' + share_url);
});

编辑:

检查了你正在使用的 w3 库后,它似乎非常有限,你应该考虑不使用它。它不提供任何在加载内容时运行回调的能力。因此,在处理 main.js 时,元素可能 a 尚未加载。但是,由于您使用的是 jQuery,因此可以使用 .load 函数。因此:

$( "header" ).load( "header.html", function() {
$(this).find('a').attr('href', 'http://www.facebook.com/sharer.php?u='+window.location.href);
});

当然,从 header 中移除 include 指令(以及其他指令,并根据需要使用加载函数加载它们)

关于javascript - 脚本不适用于包含的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41816035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com