1. 程式人生 > >click和blur沖突的問題

click和blur沖突的問題

ges 方法 text log 習慣 meta 性能 console nbsp

昨天在前端群裏討論到一個問題,大家平時做表單驗證的時候一般都有個input框和刪除按鈕,然後習慣性在失去焦點的時候去驗證輸入的內容是否正確,做驗證,發請求等等。這個時候,那個點擊刪除按鈕往往也就觸發了input的失去焦點事件,這個該咋解決呢,經過研究有以下2種方法;

1.技術分享

給失去焦點的時間加上延遲時間,讓blur時間在click事件後執行,這個方法固然能夠解決問題,但是本人並不是很推薦,因為影響性能,不到最後不用這個方法;

2.

技術分享 技術分享
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DocumentDocument</title>
</head>
<body>
<input type="text" id="box01"/><input type="button" id="box02" value="刪除"/>
<script src="http://ossweb-img.qq.com/images/js/jquery/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
    $("#box01").on("blur", function(event) {
        console.log(event.relatedTarget.id==‘box02‘);
        console.log(event.relatedTarget==document.getElementById(‘box02‘));
        console.log($(‘#box02‘)[0])
        console.log(event.relatedTarget==$(‘#box02‘)[0])
        if(event.relatedTarget==$(‘#box02‘)[0])
     {
      $("#box01").val(‘‘);
      //return;
    }else{ alert(1) } })

</script></body></html>
技術分享 技術分享

就是以上代碼了,用的是relatedTarget, w3c官網解釋,事件屬性返回與事件的目標節點相關的節點。意思就是我在失去焦點的時候,用

relatedTarget判斷一下失去焦點的時候是不是那個刪除按鈕觸發的,如果是的話就直接清空input輸入框,否則就去請求ajax.
另外說一下,其實這個relatedTarget返回的是事件節點集合,所以我們在獲取的時候要取它的第一個元素就好了,
console.log(event.relatedTarget.id==‘box02‘);
console.log(event.relatedTarget==document.getElementById(‘box02‘)); console.log(event.relatedTarget==$(‘#box02‘)[0]);
以上這三種方法都是可以的;

但是方法二有個缺陷,我們要確保刪除按鈕是button 或者 input[type="button"]做的,我試過了,如果是其它標簽,比如a,span,
event.relatedTarget 是 null,因為其他元素獲取不到焦點, 那麽即便是因為點擊 刪除按鈕 讓 input 失去了焦點, 那也得不到 relatedTarget, 反正2種方法各有利弊,自己權衡使用吧。 以上僅代表個人觀點,如有錯誤還望指正。

click和blur沖突的問題