2014-02-15 37 views
1

我已經編寫了一個輸入字段的佔位符功能函數。如果我單獨編寫開/關函數,但它在保持輸入變量和if結構時不起作用。請幫助瞭解語法或邏輯中的錯誤。輸入不起作用的函數

function placeholder(x) { 
    if (x=="1") { 
     if (document.getElementById("search_field").value=="") { 
      document.getElementById("placeholder").style.display="inline"; 
     } 
    } 
    else { 
     document.getElementById("placeholder").style.display="none"; 
     document.getElementById("search_field").focus(); 
    } 
} 

<input id="search_field" type="text" value="" onfocus="placeholder(0);" onblur="placeholder(1);"> 
<span id="field_def" onclick="placeholder(0);" > 
    <img src="mag.jpg"> 
    <p id="placeholder">Search</p> 
</span> 

回答

1

您可以只使用placeholder屬性。它被所有主要的現代瀏覽器所接受,並且可以幫助您避免添加額外的HTML標籤和JavaScript代碼。

<input type="text" name="someName" placeholder="Some Text"> 


以下爲舊的瀏覽器替代,其中placeholder無法識別:

DEMO

HTML:

<input id="search_field" type="text" value="Enter keywords..." onfocus="ph(1);" onblur="ph(0);" onclick="ph(1);"> 

的JavaScript:

function ph(x) { 
    var txtSearch = document.getElementById("search_field"); 
    if (x == 1) { 
     if (txtSearch.value == "Enter keywords...") { 
      txtSearch.value = ''; 
     } 
    } 
    else { 
     if (txtSearch.value == "") { 
      txtSearch.value = 'Enter keywords...'; 
     } 
    } 
} 
+0

它不因爲它的HTML5的舊瀏覽器兼容。 我看到很多網站同時使用佔位符屬性和JavaScript,它們在html5支持的瀏覽器上相互重疊,而且必須檢查兼容性並使用合適的瀏覽器。你不覺得這太費勁嗎? –

+0

@Sagi_Avinash_Varma查看舊版瀏覽器兼容性的編輯。 – Coder

1

評價X時嘗試沒有1引號:

function placeholder(x){ 
if(x==1){ 
    if(document.getElementById("search_field").value==""){ 
    document.getElementById("placeholder").style.display="inline"; 
    } 
} 
else{ 
    document.getElementById("placeholder").style.display="none"; 
    document.getElementById("search_field").focus(); 
    } 
} 

另外,去掉 「;」調用函數時:

<span id="field_def" onclick="placeholder(0)"> 

0

檢查函數被調用或沒有。

如果沒有,那麼改變它:

<input id="search_field" type="text" value="" onfocus="javascript:placeholder(0)" onblur="javascript:placeholder(1)">