即7不在动态生成的标记上触发事件

时间:2012-02-27 11:22:46

标签: jquery html ajax internet-explorer-7

得到了一些解决的麻烦,但想问一下,也许这是另一个解决方案。这是一种情况。 得到了aspx页面。使用函数后面的一些代码,从DB获取数据。调用的函数和通过表中的JQ返回的数据。服务器为数学html格式准备的数据。

$.ajax({
            type: "POST",
            url: "somePage.aspx/foo",
            data: "{ 'Id' : '" + ID + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#brandTable").html(msg.d);
            }

每个返回的行看起来像这样(按原样):

<tr btcsId='152' id='btcsId_152' onclick='brandClick(9,24,152)'>
<td class='DataGridItem' style='padding:3px; margin:0;font-weight:bolder;'>something<input type='hidden' id='brandID_btcsId152' value='24' brandName='something'/></td>
</tr>

表格标记:

<table class="DataGrid" id="brandTable" style="padding: 0px; margin: 0px; width:100%;border-collapse:collapse;table-layout:fixed;word-wrap:break-word;" border = "0" cellspacing="0" cellpadding="0">
    </table>

所以,问题是,那个事件onclick没有在ie7中被解雇。 ie8,ie9工作正常。经过一番思考后,我决定在填表后立即添加此代码。换句话说,每行重新启动事件。

$("[id^='btcsId_']").each(function () {
    $(this).click(function () {
    var thisID = $(this).attr("id");
    brandClick(specialityID,$("#"+thisID +" > TD > INPUT").val(),$(this).attr("btcsId"));
    });
});

之后似乎工作正常。但这是对的吗?也许还有其他方式?

2 个答案:

答案 0 :(得分:1)

不,这不正确。你不能绑定Click to future元素。

要么在元素中编写onclick签名+执行 - 要么用Live / on(更新)绑定它

$("[id^='btcsId_']").each(function () {
    $(this).live(function () {
    var thisID = $(this).attr("id");
    brandClick(specialityID,$("#"+thisID +" > TD > INPUT").val(),$(this).attr("btcsId"));
    });
});

请考虑使用On代替实时。

(&gt; 1.7)

答案 1 :(得分:1)

bast方式可以使用delegate()on()(jQuery&gt; 1.7)委托你的表元素处理这些事件:这也适用于以dinamically方式添加的元素

$("table#idofYourTable").on("click", "[id^='btcsId_']", function () {
    var thisID = this.id;
    brandClick(specialityID,$("#"+thisID +" > TD > INPUT").val(),$(this).attr("btcsId"));

});
相关问题