国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

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

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

瀏覽:146日期: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 元素的初始狀態(tài)(沒有 style 值)。

&& 運算是從左向右執(zhí)行的,只有當左邊表達式為真時,才執(zhí)行右邊的表達式。在這里既當 this.index == oBtn.length - 1,也就是點擊的是最后一個按鈕時,執(zhí)行 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的話,就執(zhí)行后面的代碼(op.style.cssText = ''),即清除樣式

a==b&&code...

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

個人不太喜歡這種寫法。

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

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

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 镇安县| 肇州县| 九龙坡区| 邹城市| 三门峡市| 巴塘县| 洛宁县| 澄江县| 大厂| 运城市| 漳浦县| 林甸县| 台湾省| 东安县| 麻城市| 专栏| 百色市| 磴口县| 翁源县| 西林县| 托克逊县| 拜城县| 西乌珠穆沁旗| 中阳县| 翼城县| 昌邑市| 安陆市| 筠连县| 平凉市| 板桥市| 秭归县| 石狮市| 上虞市| 乌审旗| 大渡口区| 应城市| 鹤峰县| 泰顺县| 峨边| 中牟县| 永顺县|