1

There is a table on a page which I update over ajax. There are some scripts those use content of a table. For instance, one of them uses "Check all / Uncheck all" checkBox on a table to check/uncheck the other checkboxes on that table.

When I do an ajax request, it returns almost the same content of a table. At least, it's definitely correct and should not destroy the functionality of the scripts. However, after that none of the scripts no longer work. Why?

For example, here is the part of a javascript code at *.js file:

$(document).ready(function() {
  $("#check-all").change(function(){
      $(".my_table input[type=checkbox]").prop('checked', this.checked);
    });
});

Before executing ajax, request everything is working well. Note that ajax doesn't return any javascript code, all javascript code is located in an external js file.

4

2 に答える 2

5

document.ready に追加されたイベントハンドラーを使用しているため、その後に追加されたものにはイベントがありません。

jQuery 1.7 以降では、on を使用できます。

$(document).on("change", "#check-all", function(){ ... });

他のオプションは、ページのコンテンツを更新するときにコードを思い出して、持っているものを保持することです。

function addChangeEvent() {
  $("#check-all").change(function(){
      $(".my_table input[type=checkbox]").prop('checked', this.checked);
    });
}

$(document).ready(function() {
    addChangeEvent();
});

そしてあなたのAjax呼び出しで

$("#foo").load("xxx.html", function(){ addChangeEvent()l });
于 2013-01-09T16:24:20.690 に答える
2

イベントは古いページ コンテンツに添付されます。そのコンテンツを置き換えると、イベントはそれに伴います。

代わりに、$("#check-all").on("change",function() {...});私は jQuery の専門家ではありませんが、要素が変更されてもイベント ハンドラーが保持されると信じています。

于 2013-01-09T16:25:15.343 に答える