2014-02-07 84 views
0

我使用html和javascript製作表單。但是當我點擊輸入文字時,我想改變焦點。我有建立一個功能,但我怎樣才能使這個功能全球,以將其用於其它輸入文字......不是建立每個輸入文字的功能..不同參數的調用函數

我的功能是這樣的:

function changefocus() { 
    var pass = document.getElementById('pass_id'); 
     if (pass.value == 'Password'){ 
    pass.value = ''; 
    pass.style.color='#000' 

     }} 

和HTML的部分是這樣的:

<input type="text" id="pass_id" name="pass" value="Password" required="required" 
     onfocus="changefocus()"> 

我試圖解決我的proble這樣的,但這並不功能... 我給的參數,我的功能

function changefocus(a) { 
     var pass = document.getElementById('a'); 
      if (pass.value == 'Password'){ 
     pass.value = ''; 
     pass.style.color='#000' 

      }} 

,然後我改變像下面的HTML部分:

<input type="text" id="pass_id" name="pass" value="Password" required="required" 
      onfocus="changefocus(pass_id)"> 

能否請你幫我...我該如何解決這個問題?在此先感謝

現在我想,當我離開輸入文本沒有任何書面方式......我想使用的onchange()像下面輸入文本不爲空,但它的功能:

function fillemptyform(pass2) { 

     if (pass2.value.length==0){ 
    pass2.value = 'Password'; 
    pass2.style.color='#000'; 

     }} 

<input type="text" id="pass_id" name="pass" value="Password" required="required" 
     onfocus="changefocus(this)" onchange="fillemptyform(this)"> 

我該怎麼做?

+0

它看起來就像你正在實施的佔位符。你爲什麼不使用HTML5的'placeholder'屬性? – Barmar

回答

3

您需要在調用changefocus函數時引用ID,並且在使用參數變量時引用而不是

function changefocus(a) { 
    var pass = document.getElementById(a); 
    if (pass.value == 'Password'){ 
     pass.value = ''; 
     pass.style.color='#000' 
    } 
} 

<input type="text" id="pass_id" name="pass" value="Password" required="required" 
     onfocus="changefocus('pass_id')"> 

如果ID將永遠是一個包含onfocus屬性的元素,你可以做這樣的:

<input type="text" id="pass_id" name="pass" value="Password" required="required" 
     onfocus="changefocus(this)"> 

function changefocus(pass) { 
    if (pass.value == 'Password'){ 
     pass.value = ''; 
     pass.style.color='#000' 
    } 
} 
+0

非常感謝...你幫了我很多。但是如果我希望當我從沒有寫入任何內容的輸入文本移動到焦點時,我希望輸入文本再次獲取值密碼,而不是空的?我怎樣才能做到這一點?我正在嘗試使用onchange,但它不起作用... – user3272713

+0

我發佈了上面的新函數...請幫助我 – user3272713

+0

使用'onblur'而不是'onchange'。因爲如果表單最初是空白的而您將其留空,則不會更改。 – Barmar

0

通行證this給函數作爲參數。 this將被分配引發事件的元素。

HTML

<input type="text" id="pass_id" name="pass" value="Password" required="required" 
      onfocus="changefocus(this)"> 

的Javascript

function changefocus(elem) { 
    if (elem.value == 'Password'){ 
     elem.value = ''; 
     elem.style.color='#000' 
    } 
} 

JS小提琴:http://jsfiddle.net/Vu3RR/

相關問題