Javascript ajax 语法来创建 html 行

Javascript ajax syntax to create html row

本文关键字:html 创建 ajax 语法 Javascript      更新时间:2023-09-26

我需要在javascript函数中使用ajax创建一行,但是我很难找到正确的语法。

这是我想要得到的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>

提前感谢!

不要进入脏字符串连接,而是使用更干净的代码。

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);    }));

在纯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);

另一种解决方案(很丑陋,不推荐):

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)