您的位置:首頁技術文章
文章詳情頁

javascript - js,有幾行代碼不太明白?

瀏覽:108日期:2023-02-25 18:24:09

問題描述

<!Doctype html><html lang='en> <head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><title>控制p屬性</title><script> var changeStyle = function(elem, attr, value) {elem.style[attr] = value }; window.onload = function() {var oBtn = document.getElementsByTagName('input');var op = document.getElementById('p1');var oAtt = ['width', 'height', 'background', 'display', 'display'];var oVal = ['200px', '200px', 'red', 'none', 'block'];for (var i = 0; i < oBtn.length; i++) { oBtn[i].index = i; oBtn[i].onclick = function() {this.index == oBtn.length - 1 && (op.style.cssText = '');changeStyle(op, oAtt[this.index], oVal[this.index]) }} };</script> </head> <body><p id='outer'> <input type='button' value='變寬' /> <input type='button' value='變高' /> <input type='button' value='變色' /> <input type='button' value='隱藏' /> <input type='button' value='重置' /> <p id='p1'></p></p> </body></html>

1.為什么要邏輯運算?2.this.index 與 op.style.cssText之間是怎么樣的關系,能簡單說一下嗎?

問題解答

回答1:

那句的意思是:如果點擊的按鈕是“重置”,則把 p1 元素的 cssText 清空。也就是重置了 p1 元素的初始狀態(沒有 style 值)。

&& 運算是從左向右執行的,只有當左邊表達式為真時,才執行右邊的表達式。在這里既當 this.index == oBtn.length - 1,也就是點擊的是最后一個按鈕時,執行 op.style.cssText = ''。

這種寫法不值得提倡,閱讀性很差,不是一個好的寫法。正常的寫法是:

if(this.index === oBtn.length - 1) { op.style.cssText = ''}

this.index 就是保存了按鈕的序號,用于判斷點擊的是哪個按鈕。在這里不能直接用 i 來表示,這是 JavaScript 一個著名的缺陷。

回答2:

this.index == oBtn.length - 1 && (op.style.cssText = '');

表示:如果是最后一個btn的話,就執行后面的代碼(op.style.cssText = ''),即清除樣式

a==b&&code...

相當于if(a==b){code....}

個人不太喜歡這種寫法。

2.this.index 與 op.style.cssText之間是怎么樣的關系

this.index 是按鈕的序號op.style.cssText = ''表示清除op的樣式。

標簽: JavaScript
相關文章:
国产综合久久一区二区三区