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. python - 數據與循環次數對應不上2. mysql - 把一個表中的數據count更新到另一個表里?3. 請教使用PDO連接MSSQL數據庫插入是亂碼問題?4. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處5. Python爬蟲如何爬取span和span中間的內容并分別存入字典里?6. 視頻文件不能播放,怎么辦?7. mysql 查詢身份證號字段值有效的數據8. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題9. node.js - nodejs開發中常用的連接mysql的庫10. 黑客 - Python模塊安全權限
