2012-08-06 51 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