JS常用技巧

2022-09-16 21:57:35 字數 852 閱讀 8126

獲取事件的產生dom  

var source =event.srcelement;(ie)

var source =event.target;(火狐等其他瀏覽器)

$(source).blur();

//使用例項1

varesrc;

if(window.event)

else

//使用例項2

if(event.srcelement) esrc=event.srcelement;

else esrc=event.targer;

view code

回車鍵的處理:

要控制這些行為,不需要借助js,瀏覽器已經幫我們做了這些處理,這裡總結幾條規則:

如果表單裡有乙個type="submit"的按鈕,回車鍵生效。

如果表單裡只有乙個type="text"的input,不管按鈕是什麼type,回車鍵生效。

如果按鈕不是用input,而是用button,並且沒有加type,ie下預設為type=button,fx預設為type=submit。

其他表單元素如textarea、select不影響,radio checkbox不影響觸發規則,但本身在fx下會響應回車鍵,在ie下不響應。

var key =event.keycode;

varsource;

if (event.srcelement) source =event.srcelement;

if (event.target) source =event.target;

if (key == 13)

view code

JS常用技巧

三元運算子 let hungry true let eat hungry yes no 數字和字串互 let num 15 let s num let n s 相當於 0 字串 物件和陣列互 let arr value1 value2 value3 let arrobject let key obj...

JS 陣列常用技巧

刪除陣列的重複項 var uniquefruits array.from new set fruits console.log 刪除陣列的重複項 uniquefruits 替換陣列中的特定值 var usernames 小組1 小組2 小組3 小組4 小組5 usernames.splice 0,2...

js常用小技巧

陣列扁平化 const arr 1,2,3,4,5,6,7,8 console.log arr.flat infinity 1,2,3,4,5,6,7,8 console.log arr.join split 1 2 3 4 5 6 7 8 console.log arr.tostring spli...