2012-08-06 49 views
0

我想改變我的窗體的一些輸入的類在class ='mypost_title'onclick。javascript更改類的多個輸入onclick

我嘗試這樣做,這是行不通的

<a href='' onclick='popup_mypost(e)'>change me</a> 
<a href='' id=edit-href onclick='popup_mypost(e)'>back me</a> 

<script> 
    function popup_mypost(e) 
    { 
     var inputs = document.getElementsByClassName("mypost_title"); 
     for(var i = 0; i < inputs.length; i++) 
      { 
      inputs[i].className = "change"; 
      } 

     var edit_href = document.getElementById("edit-href"); 
     edit_href.onclick = function() 
     { 
      var inputs = document.getElementsByClassName("change"); 
      for(var i = 0; i < inputs.length; i++) 
       { 
       inputs[i].className = "mypost_title"; 
       } 
     } 
    } 
</script> 
+0

你介意使用jQuery? – freebird 2012-08-06 10:14:46

+3

我認爲它:getElementsByClassName(..);你錯過了元素 – 2012-08-06 10:15:17

+0

@Sudhir好的建議,但我不認爲這適用於crossbrowser。 – Undefined 2012-08-06 10:15:36

回答

0

改變這一行,並嘗試:

var inputs = document.getElementsByClassName("mypost_title");

1

對於一個jQuery方法見下文我的代碼。我個人認爲這更容易閱讀和遵循。此外,這將完全跨瀏覽器!

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<script> 

$(document).ready(function() { 
    $(".mypost_title").each(function() { 
     $(this).addClass("change"); 
    }); 
}); 

</script> 

我已經快速檢查了與getElementsByClassName的跨瀏覽器兼容性,結果非常令人驚訝。 IE8及以下版本不支持這個!請在此處查看tests


編輯

我猜一點點你在找什麼在這裏。這是我的解釋:

當其中一個div被點擊時,你想添加change類到被點擊的類並從其他所有類中刪除change類?

在這種情況下,你會怎麼做:

//This focus event will fire when the user "focuses" on an input 
$(".mypost_title").focus(function() { 
    $(this).removeClass("mypost_title"); 
    $(this).addClass("change"); 
}); 

//This blur event will fire when the user clicks outside the input, or tabs out etc 
$(".mypost_title").blur(function() { 
    $(this).removeClass("change"); 
    $(this).addClass("mypost_title"); 
}); 
+0

如何我知道這個函數是我打電話給我的嗎?我有onclick ='popup_mypost(e)'。既然你告訴我getElementsByClass不能在其他瀏覽器上工作,現在我想用你提議的 – 2012-08-06 10:37:28

+0

@IvorySantos請檢查我的更新的答案,這是你在找什麼?如果不是,你可以展示一些你的JavaScript嗎? – Undefined 2012-08-06 10:44:12

+0

我更新了我的問題,對不起,我真的不知道jQuery。首先,當點擊時,cl屁股必須=「改變」。然後,當後面點擊,類必須=「mypost_title」謝謝 – 2012-08-06 11:00:13