javascript - 如何獲取點擊事件點擊后前一個后一個的值。
問題描述
for (var i = 0; i < pic.length; i++) {pic[i].onclick = function () { var aA = this.getAttribute('href'); return false;} }
已經for循環遍歷綁定點擊事件,點擊圖片一的時候,已經可以獲取到標簽里面href的值(備注:href是A標簽里面額跳轉鏈接,return false是為了不跳轉),現在我想獲取到點擊當前圖案時候,上一個標簽和下一個標簽的href的值,讓中間圖片顯示圖案一,,左邊圖案顯示圖案4,右邊圖案顯示圖案2,該如何操作?
問題解答
回答1:for (var i = 0; i < pic.length; i++) { pic[i].index=i; pic[i].onclick = function () {var aA = this.getAttribute('href');//如果當前是第一個,沒有上一個,值獲取下一個if(this.index===0){ var aANext=pic[this.index-1].getAttribute('href');}//如果當前是最后一個,沒有下一個,只獲取上一個else if(this.index===pic.length-1){ var aAPrev=pic[this.index-1].getAttribute('href');}//否則上下都獲取else{ var aAPrev=pic[this.index-1].getAttribute('href'); var aANext=pic[this.index-1].getAttribute('href');}return false; }}回答2:
謝謝,你這種方法很好,在元素,及相鄰的元素設置一個index的屬性,我看明白了我現在是這樣寫的,不過還要出來,如何讓點第一個的時候出現第四個圖<script>
var pic = document.getElementById(’pic’).getElementsByTagName(’a’);var pid = document.getElementById(’pid’).getElementsByTagName(’img’);for (var i = 0; i < pic.length; i++) { pic[i].onclick = function () {var aA = this.getAttribute('href');var pid = document.getElementById(’pid’);pid.setAttribute('src', aA);var aB = this.parentNode.previousSibling.firstChild.getAttribute(’href’)pid.previousSibling.setAttribute(’src’, aB);var aC = this.parentNode.nextSibling.firstChild.getAttribute(’href’)pid.nextSibling.setAttribute(’src’, aC);
return false; }}
</script>
相關文章:
1. css3 - [CSS] 動畫效果 3D翻轉bug2. python - Django分頁和查詢參數的問題3. javascript - 百度echarts series數據更新問題4. MySQL客戶端吃掉了SQL注解?5. javascript - JS設置Video視頻對象的currentTime時出現了問題,IE,Edge,火狐,都可以設置,反而chrom卻...6. php自學從哪里開始?7. python小白的基礎問題 關于while循環的嵌套8. 求大神幫我看看是哪里寫錯了 感謝細心解答9. phpstady在win10上運行10. javascript - 圖片能在網站顯示,但控制臺仍舊報錯403 (Forbidden)
