获取动态创建行的id
Getting id of dynamically created row
在id为productTable的表中,我使用以下jquery代码添加行:
$('#productTable').html("");
for (var i = 0; i < result.count; i++)
{
$('#productTable').append('<tr id=' + result.productArray[i].productID + 'class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
}
和我附加一个处理程序到这些行使用:
$("#productTable").on("click","tr",function(event){
alert(this.id);
});
但我得到的ID是表的而我想要的是被点击行的ID
帮助问题是你所附加的是无效的HTML
$('#productTable').append(
'<tr id=' + result.productArray[i].productID + 'class="product">
<td>
<a> '+result.productArray[i].productName+'</a>
</td>
</tr>'
);
请仔细查看,ID周围没有引号,ID和类之间也没有空格分隔。
基本上你最后会得到
<tr id=idclass="product">
<td>
<a>text</a>
</td>
</tr>
正确的代码是
$('#productTable').append('<tr id="' + result.productArray[i].productID + '" class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
Try This:
$('#productTable').html("");
for (var i = 0; i < result.count; i++)
{
var obj = $('<tr id=' + result.productArray[i].productID + 'class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
$(obj).click(function(event){
alert($(this).attr("id"));
});
$('#productTable').append(obj);
}
在动态创建元素时绑定事件。这是你想做的另一种方法。
$('#productTable').html("");
for (var i = 0; i < result.count; i++)
{
$('#productTable').append('<tr id=" + result.productArray[i].productID + " class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
$('#'+result.productArray[i].productID).bind('click',function(){
//put your code here
});
}
<标题>演示 标题>相关文章:
- 正在为循环创建唯一id
- 在JavaScript中创建全局唯一ID
- SoundCloud API-基于系统中的ID创建用户配置文件
- 如何为动态创建的元素分配唯一的id-Javascript
- 使用jQuery创建具有不同类名或ID的多个元素
- 单击旧列表只显示上次创建的id,应在单击时显示列表id
- 更新脚本以针对具有递增 ID 的新创建的表行运行
- 使用带有附加自动递增编号的当前 DATE 创建 ID
- 使用jquery删除id创建的元素
- 如何使用来自其他 json 对象的 id 和父 id 创建像树结构一样的 json
- 无法使用客户 ID 创建 Braintree 客户端令牌
- 如何在 JavaScript 中对以 # 开头的 ID 创建 OnClick 事件
- 使用按钮ID创建Javascript幻灯片
- SailsJS-使用自定义ID创建新记录
- 如何获取由填充对象中的特定许可证 ID 创建的记录
- 使用生成的ID创建JavaScript集合的最具性能的方法
- 在类似视图上使用class而不是id创建新视图
- 在Id创建之前使用getElementById
- 使用jQuery选择器从外部文件通过id创建Javascript对象
- 如何为Div类和类内的ID创建悬停效果