附加。点击的方法来通过Ajax加载的类方法来、加载、Ajax

2023-09-10 19:00:32 作者:西阁的酒

我越来越略输为被附加到。点击事件动态加载其他页面的数据...

I'm getting slightly lost as to .click events being attached to dynamically loading data from other pages...

我有一个主表。各行的第一列是可点击的加载子表。所述子表应当采取行动以同样的方式,点击第一值打开子子表

I have a main table. The first column of each row is clickable to load a sub-table. Said sub-table should act in the same way, clicking the first value opening a sub-sub-table.

<table>
  <tr>
    <td class="ClickMe" id="1">Title Of Row</td>
    <td>Main Data1</td>
    <td>Main Data2</td>
  </tr>
  <tr>
    <td class="ClickMe" id="2">Title Of Row</td>
    <td>Main Data1</td>
    <td>Main Data2</td>
  </tr>
</table>
<script type="text/javascript">
$(function () {
  function LoadSub1(inputRowID)
  {
    $.ajax({
      url: 'SomePage.php',
      data: 'ID='+inputRowID,
      success: function(data){
        $("#Details1").html(data);
      }
    })
  }

  $("td.ClickMe").click(){
    // remove previous added row
    $("#AddedRow").remove();

    // Get new id
    var RowID = $(this).attr("id");

    // Create new row with <div> to populate
    $(this).after("<tr id="AddedRow"><td><div id="Details1"></div></td></tr>");

    // Load sub-table into <div>
    LoadSub1(RowID);
  }

  $("td.ClickMe2").click(){
    var subRowID = $(this).attr("id");
    // some further table loading based on sub-table id value
  }
}
</script>

如果在SomePage.php与标签表,在主页上。点击()事件无法触发。

If the "SomePage.php" has a table with a tag, the .click() event in the main page fails to trigger.

有什么建议?帮助最AP preciated。

Any suggestions? Help most appreciated.

推荐答案

绑定。点击的事件处理程序()仅在DOM应用到当前的元素。要绑定的事件处理程序的元素,现在和将来,使用 .live() .delegate()

The event handlers bound with .click() are only applied to elements currently in the DOM. To bind event handlers to elements now and in the future, use .live() or .delegate():

使用 .delegate()(推荐):

$("#Details1").delegate("td.ClickMe", "click", function () {
    // remove previous added row
    $("#AddedRow").remove();

    // Get new id
    var RowID = $(this).attr("id");

    // Create new row with <div> to populate
    $(this).after("<tr id='AddedRow'><td><div id='Details1'></div></td></tr>");

    // Load sub-table into <div>
    LoadSub1(RowID);
}

使用 .live()

$("td.ClickMe").live("click", function () {
    // remove previous added row
    $("#AddedRow").remove();

    // Get new id
    var RowID = $(this).attr("id");

    // Create new row with <div> to populate
    $(this).after("<tr id='AddedRow'><td><div id='Details1'></div></td></tr>");

    // Load sub-table into <div>
    LoadSub1(RowID);
}

(也定格在你的附加HTML引号)

(also fixed the quotation marks in your appended html)