Jquery change href属性仅在添加alert()函数时有效

Jquery change href attribute only works when I add an alert() function

本文关键字:函数 有效 alert 添加 href change 属性 Jquery      更新时间:2023-09-26

我正在使用jquery将侧边栏加载到我的每个页面中,侧边栏包含一个故事名称、日期和内容类型的列表(故事、文章、新闻等等(,这些内容类型被放置在一个无序列表中,当每个页面加载时,我使用jquery的.load((函数将侧边栏信息加载到当前页面的无序列表中,加载侧边栏信息后,我使用另一个脚本,将侧边栏中当前故事的href设置为#。问题是,将href设置为#的代码只有在我将警报放在函数前面时才有效。

流程如下:

用户点击一个故事(让我们把故事称为nothing.html(

nothing.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../../../css/reset.css">
    <link rel="stylesheet" href="../../../../css/index.css">
    <script type="text/javascript" src="../../../../js/jquery.js"></script>
    <script type="text/javascript" src="../../../../js/storyLoadSidebar.js"></script>
    <script type="text/javascript" src="../../../../js/disableLink.js"></script>
    <title> Nothing </title>
</head>
<body>
    <div id="container">
        <div id="main">
            <article>
                <header>
                    <h3> Nothing Here </h3>
                    <time pubdate="pubdate"> July 19, 2011 </time>
                </header>
                <p> I said there was nothing here, yet. </p>
            </article>
        </div>
        <div id="listWrapper">
            <div id="storyList">
                <ul></ul>
            </div>
        </div>
    </div>
</body>
</html>

storyLoadSidebar.js

$(document).ready(function() {
    $("ul").load("../../../../sidebar.html ul");
});

边栏.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>  
    <ul>
        <li>
            <div class="catDate">
                <p> Nothing </p>
                <time pubdate="pubdate"> 2011-07-19 </time>
            </div>
            <div class="storyTitle">
                <a id="nothing" href="stories/2011/07/19/nothing.html"> Nothing Here, Yet. </a>
            </div>
        </li>
    </ul>
</body>
</html>

然后最后脚本禁用链接:

disableLink.js

$(document).ready(function() {
    var fullPath = window.location.pathname;
    var pageName = fullPath.substring(fullPath.lastIndexOf('/') + 1).replace('.html', '');
    $('#' + pageName).attr('href', '#');
});

整件事只适用于我在href修改之前向disableLink.js添加一个警告,如下所示:

$(document).ready(function() {
    var fullPath = window.location.pathname;
    var pageName = fullPath.substring(fullPath.lastIndexOf('/') + 1).replace('.html', '');
    alert('now it will work');
    $('#' + pageName).attr('href', '#');
});

这里的问题是什么?为什么只有在我添加警报的情况下它才能工作?

原因是$("ul").load("...")需要一些时间才能加载。

你可以给它分配一个回调函数,这样下一段代码只有在完成时才能运行

$("ul").load("../../../../sidebar.html ul",function () {
   var fullPath = window.location.pathname;
   var pageName = fullPath.substring(fullPath.lastIndexOf('/') + 1).replace('.html', '');
   $('#' + pageName).attr('href', '#');
})