2014-12-07 19 views
2

我需要在javascript函數中創建一個帶有ajax的行,但是我在查找正確的語法時遇到了很多麻煩。javascript ajax語法創建html行

這是HTML最終的結果,我想:

<td style="text-align:center"> 
<input type="image" src="nienteico.png" style="cursor:pointer; width:40px; height:40px" id="5.51" class="ajaxEdit" onclick="cambiastato(5.51)"> 
</td> 

,這是修改需要的JS代碼:

<td style="+'text-align:center'+"><input type="+'image'+" src="+'nienteico.png'+" style="+'cursor:pointer; width:40px; height:40px'+" id="+'5.51'+" class="+'ajaxEdit'+" onclick="+'cambiastato(5.51)'+"></input></td> 

最後,這是我獲得使用JS的HTML我已經寫過:

<td style="text-align:center"><input type="image" src="nienteico.png" style="cursor:pointer;" width:40px;="" height:40px="" id="5.51" class="ajaxEdit" onclick="cambiastato(5.51)"></td> 

在此先感謝!

+0

不要試圖用搗碎串在一起寫HTML JS。使用DOM。 'createElement','setAttribute','appendChild'等。管理起來更容易。 – Quentin 2014-12-07 12:48:35

+0

最新的問題是什麼?缺失的新行? – elcuco 2014-12-07 12:48:36

+0

對不起,但我想你應該先問一下[this](http://eloquentjavascript.net/),然後再問問關於JavaScript的問題,然後討論關於AJAX本身[入門AJAX](https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) – Givi 2014-12-07 12:49:29

回答

2

不要進入髒字符串連接,而是去尋找更乾淨的代碼。

var row = $('<td />', { style: "text-align:center"}).append($('<input />', { 
    type: 'image', 
    src: 'nienteico.png', 
    'class': 'ajaxEdit' 
}).css({ 
    id: '5.51', 
    cursor: 'pointer', 
    width: '40px', 
    height: '40px', 
}).click(function() { cambiastato(5.51); })); 
+0

謝謝!如果我需要「之後」功能,我如何使用您的代碼?例如:$(「#」+ response.last_id +「」)。closest(「tr」)。after(row);其中「行」是我們現在創建的行 – Peppegiuseppe 2014-12-07 13:12:09

+1

@Peppegiuseppe現在您可以添加'.after(row)' – 2014-12-07 13:17:55

+0

是的!很好的答案,現在..我想創建一個,裏面有4個​​(用我以前展示的相同方式製作),我該如何使用您的解決方案?謝謝 – Peppegiuseppe 2014-12-07 13:23:43

2

嘗試這種在純javascript:

var td = document.createElement('td'); 
    td.style.textAlign="center"; 
var input = document.createElement('input'); 
    input.type="image"; 
    input.src="nienteico.png"; 
    input.style.cursor="pointer"; 
    input.style.width="40px"; 
    input.style.height="40px"; 
    input.setAttribute("id","5.51"); 
    input.className="ajaxEdit"; 
    input.onClick = function() { cambiastato(5.51); }; 

td.appendChild(input); 
+0

那麼插入多個td怎麼辦? 例如這種結構:​​​​ – Peppegiuseppe 2014-12-07 13:08:27

+2

你可以試試'for'循環和內用我的代碼使用不同的值 – 2014-12-07 13:13:21

1

另一種解決方案(這是醜陋的,不推薦):

var html_template = 
'<td style="%style%">' + 
    '<input type="%img_type%" src="%img_src%" style="%img_style%" id="%img_id%" class="ajaxEdit" onclick="cambiastato(5.51)">' + 
'</td>'; 

html_template = html_template.replace("%style%", "text-align:center"); 
html_template = html_template.replace("%img_type%", "image"); 
html_template = html_template.replace("%img_src%", "neinteico.png"); 
html_template = html_template.replace("%img_id%", "5.51"); 
html_template = html_template.replace("%img_style%", "cursor:pointer; width:40px; height:40px"); 

alert(html_template)