2016-04-13 40 views
2

這是我的HTML代碼如何我可以顯示和隱藏輸入標籤,而焦點進出

<label for="first_name">First Name</label> 
<input class="w3-input" type="text" name="first_name" id="first_name"> 

<label for="last_name">Last Name</label> 
<input class="w3-input" type="text" name="last_name" id="last_name"> 

,而我輸入點擊我需要隱藏的標籤,以得到結果我創建下面的jQuery代碼,但不加工。

$(document).ready(function(){ 

$(".w3-input").click(function(){ 
    var item_select = this.id; //getting id of clicked item 

    $(item_select).focusin(function(){ 
     $(this).prev("label").hide(); //hide label of clicked item 
    }); 
     $(item_select).focusout(function(){ 
     $(this).prev("label").show(); 
    }); 
}); 

}); 

有什麼錯我的代碼中的任何一個幫助我嗎?如果你還沒有點擊輸入刪除click事件的作品確定

DEMO

回答

2

問題是要註冊在click處理程序focusin處理程序,當點擊發生冷杉的的focusIn被觸發,則點擊,所以第一次點擊時沒有focusin處理程序被觸發。還有其他一些問題,例如每次點擊都會增加越來越多的處理程序。

沒有必要爲click事件

$(function() { 
 

 
    $(".w3-input").focus(function() { 
 
    $(this).prev("label").hide(); //hide label of clicked item 
 
    }).blur(function() { 
 
    $(this).prev("label").show(); 
 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label for="first_name">First Name</label> 
 
<input class="w3-input" type="text" name="first_name" id="first_name"> 
 

 
<label for="last_name">Last Name</label> 
 
<input class="w3-input" type="text" name="last_name" id="last_name">

2

使用$('#'+item_select)

$(document).ready(function(){ 

$(".w3-input").click(function(){ 
    var item_select = this.id; //getting id of clicked item 
     console.log(item_select) 
    $('#'+item_select).focusin(function(e){//add # to target id 
     $(this).prev("label").hide(); //hide label of clicked item 
    }); 
     $('#'+item_select).focusout(function(){//add # to target id 
     $(this).prev("label").show(); 
    }); 
}); 

}); 

demo

您的解決方案是行不通的你並不需要click

$(document).ready(function(){ 
    $(".w3-input").focusin(function(){ 
    $("label[for='" + $(this).attr("id") + "']").hide(); 
    }); 
    $(".w3-input").focusout(function(){ 
    $("label[for='" + $(this).attr("id") + "']").show(); 
    }); 
}); 

Fiddle