【问题标题】:Part of jQuery code is not working with .ejs file部分 jQuery 代码不适用于 .ejs 文件
【发布时间】:2021-08-26 13:23:42
【问题描述】:

我正在使用 .ejsnodeJS。 我的jQuery 代码的部分 不起作用。此外,它不会在控制台中引发任何错误。

jQuery 连接到文档末尾的index.ejs,如下所示:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>
<script src="/js/app.js"></script>

点击这里:

<ul class="nav__right">
     <li class="nav__link" id="delivery-link">Доставка</li>
     <li class="nav__link nav__link-ml" id="firms-link">Фирмам</li>
     <li class="nav__link nav__link-ml" id="contacts-link">Контакты</li>
</ul>

我希望向下滑动到也有 id's 的块。

jQuery 代码如下所示:

$("#logo-link").click(function() {
    window.scrollTo({ top: 0, behavior: 'smooth' });
}); // This part is working!

$("#about-link").click(function() {
    $('html,body').animate({
        scrollTop: $("#about").offset().top-navHeight},
        'slow');
});

$("#products-link").click(function() {
    $('html,body').animate({
        scrollTop: $("#products").offset().top-navHeight},
        'slow');
});

$("#find-link").click(function() {
    $('html,body').animate({
        scrollTop: $("#find").offset().top-navHeight},
        'slow');
});

顶部的部分正在工作,其他部分不工作。 我已经用基本的 .html 文件测试了相同的代码,它运行良好。 我想,问题是由于.ejs而出现的,但是,绝对无法解决这个问题。

提前谢谢你。

【问题讨论】:

  • 点击事件监听器是否触发?
  • 是的,它们有效。
  • 如果没有证明问题的minimal reproducible example 就很难提供帮助

标签: javascript jquery ejs


【解决方案1】:

正确的语法是:

//Smooth scrolling with links
$('a[href*=\\#]').on('click', function(event){     
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});

// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
  $('html,body').animate({scrollTop:$(location.hash).offset().‌​top}, 500);
});

简化:干

function smoothScrollingTo(target){
  $('html,body').animate({scrollTop:$(target).offset().​top}, 500);
}
$('a[href*=\\#]').on('click', function(event){     
    event.preventDefault();
    smoothScrollingTo(this.hash);
});
$(document).ready(function(){
  smoothScrollingTo(location.hash);
});

href*=\\#的解释:

  • * 表示它与包含 # 字符的内容匹配。因此只匹配 anchors。有关此含义的更多信息,请参阅here
  • \\ 是因为 # 是 css 选择器中的特殊字符,所以我们必须对其进行转义。

【讨论】:

    猜你喜欢
    • 2019-11-10
    • 2019-05-27
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2016-08-13
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多