1
我使用jquery將邊欄加載到每個頁面中,邊欄包含一個故事名稱列表,日期和內容類型(故事,文章,新聞,無論)這是放置在一個無序的列表中,當每個頁面加載時我使用jquery的.load()函數加載邊欄信息到當前頁面的無序列表中,一旦側邊欄信息已加載我使用另一個腳本設置當前故事在側邊欄中的href爲#。問題在於,將href設置爲#的代碼片段只在我將函數放在函數前面時才起作用。只有當我添加一個alert()函數時,jquery change 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");
});
sidebar.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', '#');
});
整個事情只能我添加警報disableref.js在href修改之前就像這樣:
$(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', '#');
});
這裏有什麼問題,爲什麼只有在添加警報時才起作用?
非常感謝你,我想知道是否有是有這兩種功能的一個很好的方式只能運行在一個文件中無需傳遞任何參數,這個工作完美,我瞭解了回調函數,太棒了!再次感謝! – valon
是的,這樣你就可以將它全部放在同一個文件中 – Ibu