2009-12-15 72 views
1

大家好,我試圖用'文本'輸入類型替換爲'密碼'。而且它與下面的代碼:用javascript替換輸入

function replaceT(obj){ 
      var newO=document.createElement('input'); 
      newO.setAttribute('type','password'); 
      newO.setAttribute('name',obj.getAttribute('name')); 
      obj.parentNode.replaceChild(newO,obj); 
      newO.focus(); 
      } 

但我想我以前輸入的添加類新的輸入和我想是這樣的:

function replaceT(obj){ 
      var newO=document.createElement('input'); 
      newO.setAttribute('type','password'); 
      newO.setAttribute('className' obj.getAttribute('class')); 
      newO.setAttribute('name',obj.getAttribute('name')); 
      obj.parentNode.replaceChild(newO,obj); 
      newO.focus(); 
      } 

什麼我做錯了,或者如果這是不可能的,如何手動設置新類。謝謝

回答

2

這應該在所有瀏覽器的工作:

newO.className = obj.className; 

我不知道你是否應該在setAttribute使用classNameclass,但不管是什麼,它絕對是相同getAttribute,所以這是肯定是不對的:

newO.setAttribute('className' obj.getAttribute('class')); 
+0

這完全有效..謝謝 – ant 2009-12-15 12:19:18

+0

後續..是否有可能添加onclick ..和其他事件到新創建的輸入元素? – ant 2009-12-15 12:39:51

+0

好的,這絕對有可能。對於初學者來說,你需要查看IE的* attachEvent *和所有其他的addEventListener *,但爲了絕對的兼容性,你真的想看看一個框架,比如jQuery。 – 2009-12-15 13:05:47

2
newO.setAttribute('className' obj.getAttribute('class')); 

您正在使用'className'來設置屬性,但'class'來獲取它。兩者都必須是'className'。

+0

那麼我讀了一些文章..只是困惑..反正這是解決方案,它是類或className? – ant 2009-12-15 12:13:42

+0

編輯後給出實際答案。 – 2009-12-15 12:15:47

+0

不是真的,它不起作用 – ant 2009-12-15 12:18:40

0

對不起,我在另一個方向走,但你爲什麼要更換元件,而不是隻擺在首位改變它的類型?比你不需要擔心添加相同的className到新的元素。

只是好奇。

+0

因爲我想添加標籤到字段「密碼」,如果我先改變它來輸入密碼,那麼它會被掩蓋.. razumijes:D – ant 2009-12-15 12:28:26

+0

lol :) razumijem;) – 2009-12-15 12:33:03

+0

IE(6和7,未嘗試在8)將會拋出一個異常,如果你嘗試改變'輸入'元素的類型後,它已被添加到文檔(即使您嘗試刪除它,更改它,然後重新添加它)。 – NickFitz 2009-12-15 13:29:08