1. 程式人生 > >a標簽與js的沖突

a標簽與js的沖突

... ati 代碼 func 補充 win 多個 style XA

技術分享圖片

如上圖,需要做一個頁面,點擊左邊的標題,右邊就顯示左邊標題下的子標題的集合,

html代碼如下:

<div id="newleft">
<ul>
<li><a href="" class="showList" >${guideList[0].type}</a></li>
<li><a href="" class="showList" >${guaranteeList[0].type}</a></li>
<li><a href="" class="showList" >${membeList[0].type}</a></li>
<li><a href="" class="showList" >${afterSalList[0].type}</a></li>
</ul>
</div>
<div id="newsRight">
<div class="showNewsList">
<c:forEach var="news" items="${guideList}">
<p><a class="newInfo" href="${pageContext.request.contextPath}/static/tohelpView/1/${news.nId}">${news.title}...</a></p>
</c:forEach>
</div>
<div class="showNewsList" >
<c:forEach var="newsa" items="${guaranteeList}">
<p><a class="newInfo" href="${pageContext.request.contextPath}/static/tohelpView/2/${newsa.nId}">${newsa.title}...</a></p>
</c:forEach>
</div>
<div class="showNewsList">
<c:forEach var="newsb" items="${membeList}">
<p><a class="newInfo" href="${pageContext.request.contextPath}/static/tohelpView/3/${newsb.nId}">${newsb.title}...</a></p>
</c:forEach>
</div>
<div class="showNewsList">
<c:forEach var="newsc" items="${afterSalList}">
<p><a class="newInfo" href="${pageContext.request.contextPath}/static/tohelpView/4/${newsc.nId}">${newsc.title}...</a></p>
</c:forEach>
</div>
</div>

js代碼如下:
/**
* 點擊
*/
$(document).on("click",".showList",function(){
var indexaa = 0;//在集合中的索引
var $showList = $(".showList");//按鈕集合,jQuery對象一定要帶“$”
var $div = $("#newsRight").children(".showNewsList");//顯示集合
indexaa=$showList.index($(this));//集合中的索引
$div.hide();
$div.eq(indexaa).fadeIn();
});
問題:點擊事件始終只顯示一個相同的子標題,也就是第一個。換了好多個js寫法都是那樣。
後來發現是a標簽的問題
<a href=""
後來改成:<a href="#" 或者<a href="javascript:void(0)"
問題就解決了,<a href="javascript:void(0)"相當於一個死鏈接;<a href="#" 相當於鏈接本頁面
補充:
a標簽的onclick 事件先執行, href 屬性下的鏈接後執行(頁面跳轉或 javascript 偽鏈接),如果不想執行 href 屬性下的鏈接,onclick 需要返回 false。


a標簽與js的沖突