2012-11-29 31 views
0

有以下的jQuery代碼:如何在當前對象中添加新元素?

$(document).ready(function(){ 
     $(".translated").mouseenter(function(){ 
      $(this).html("<input type='text'/>"); 
     }); 
    }); 

而且有很多<div class="translated">項目在其文本的表格。我需要通過mouseenter事件將div塊中的文本替換爲輸入項。有用。但是我還需要在替換過程中爲輸入元素設置屬性,並且我不知道如何才能做到這一點,因爲我是JS/JQuery中的新成員。請給我一些信息。先謝謝你。

更新:對不起,我的屬性也是用JS計算的,它不是恆定的。

更新2: 算法: 1)將輸入項DIV項目的新插入的項目 2)改變高度

+1

只需設置輸入的其餘屬性作爲要設置的'類型=「文本」'或使用'$(「」)。 attr({type:'text'/ *,more attributes * /});' –

+0

你試圖設置什麼屬性,爲什麼你不能簡單地將它們寫入''標記定義? –

+0

[使用jQuery更改屬性]的可能重複(http://stackoverflow.com/questions/6972911/changing-attributes-with-jquery) – Pfitz

回答

0

爲了記錄,創建元素有一個特殊的jQuery語法。

$("<input/>", { 
    type: "text", 
    height: 100 
}).appendTo(this); 

上面插入一個input元件與type屬性設置爲textheight(CSS)設置爲100px

附加到目標元件的所產生的標記是:

<input type="text" style="height: 100px;"> 
+0

非常感謝!請告訴我,需要使用「新」關鍵字來製作新的輸入項目嗎?請給出完整代碼 – user1841247

+0

這足以滿足您的需求 – Alexander

3

只需設定輸入的其他屬性,如您正在設置type="text"像下面,

$(this).html("<input type='text' /* other attributes */ />"); 

或象下面使用,

$('<input />').attr({type: 'text'/*, more attributes*/}); 
+0

但如果我使用上一次構建,我將更改頁面右側的所有輸入項?我只需要改變一個新物品的高度attr。 – user1841247

1
var someVariable = 1 + 2; 
$(this).html("<input type='text' anotherAttribute='something' attrFromValue='" 
    + someVariable + "' />");