Javascript 尝试使用jquery添加属性时遇到问题
我需要在jquery中动态添加一行,这是我的代码:Javascript 尝试使用jquery添加属性时遇到问题,javascript,jquery,html,Javascript,Jquery,Html,我需要在jquery中动态添加一行,这是我的代码: var row = $('<tr />') .append($('<td />')) .append($('<td>' + response.nome + '</td>')) .append($('<td />', { style: "text-align:center" }).append($('<input />', {
var row = $('<tr />')
.append($('<td />'))
.append($('<td>' + response.nome + '</td>'))
.append($('<td />', {
style: "text-align:center"
}).append($('<input />', {
type: 'image',
src: 'nienteico.png',
'class': 'ajaxEdit',
id: '1.' + response.row_id
}).css({
cursor: 'pointer',
width: '40px',
height: '40px',
}).click(function() {
cambiastato('1.' + response.row_id);
})));
var行=$(“”)
.附加($('')
.append($(''+response.nome+'')
.附加($(''){
样式:“文本对齐:居中”
}).附加($(''){
键入:“图像”,
src:'nienteico.png',
“类”:“ajaxEdit”,
id:'1.+response.row\u id
}).css({
光标:“指针”,
宽度:“40px”,
高度:'40px',
})。单击(函数(){
cambiastato('1.'+响应。行id);
})));
特别是,关于最后一个元素,我希望得到'id'属性和一个'onclick函数'。比如:
<tr>
<td></td>
<td>uytredsgfh</td>
<td style="text-align:center">
<input type="image" src="nienteico.png" style="cursor:pointer; width:40px; height:40px" id="1.15" class="ajaxEdit" onclick="cambiastato(1.15)">
</td>
</tr>
uytredsgfh
前两个元素写得很正确,但不幸的是,最后一个元素就是这样写的(缺少id属性和onclick函数!)
有什么帮助或建议吗?谢谢您的代码是正确的。jQuery没有向元素添加属性,而是向DOM添加属性。换句话说,即使在工作时,它也不会显示在标记中。尝试向侦听器添加一个
console.log
语句,并进行尝试-应该可以
另一方面,有一些最佳实践可能有助于保持代码更干净、更易于维护
$
作为变量名的前缀。在您的示例中,这将是$row
$input
元素拉入它自己的变量中祝你好运 这就是你所期望的 您的
id
无效,因为它以数字开头-请参阅。jQuery可能因此拒绝了它
click事件不作为标记的属性写入。相反,它作为标记所代表的DOM元素的属性连接起来。如果您将输入
放在页面上并单击它,您可能会发现它是有效的
如果您确实希望显式地将onclick
和其他属性输出到标记中,您只需在初始标记创建调用中设置它们:
var row = $('<tr />')
.append($('<td />'))
.append($('<td>' + response.nome + '</td>'))
.append($('<td style="text-align:center" />')
.append($('<input onclick="cambiastato(1.' + response.row_id + ');" type="image" src="nienteico.png" class="ajaxEdit" id="1.' + response.row_id + '" />')
.css({
cursor: 'pointer',
width: '40px',
height: '40px',
})
));
var行=$(“”)
.附加($('')
.append($(''+response.nome+'')
.append($('')
.append($('')
.css({
光标:“指针”,
宽度:“40px”,
高度:'40px',
})
));
var row = $('<tr />')
.append($('<td />'))
.append($('<td>' + response.nome + '</td>'))
.append($('<td style="text-align:center" />')
.append($('<input onclick="cambiastato(1.' + response.row_id + ');" type="image" src="nienteico.png" class="ajaxEdit" id="1.' + response.row_id + '" />')
.css({
cursor: 'pointer',
width: '40px',
height: '40px',
})
));