2013-10-29 47 views
5

我有table.tablesorter元素經常改變使用AJAX。我想在點擊時添加事件處理程序,只要點擊它的標題就會將其委託給table.tablesorter th.class元素。我是使用jQuery的新手。因此,我嘗試將以下jQuery腳本放入Chrome Web Console。如何添加jQuery .on點擊Tablesorter th?

jQuery腳本:

$('#table-content').on(
    'click', 
    '.tablesorter thead tr th', 
    function() {alert(); } 
); 

我的HTML:

<div id="table-content"> 
    <table class="tablesorter"> 
     <thead> 
      <tr> 
       <th class="header">No.</th> 
       <th class="header">Name</th> 
       <th class="header">Phone</th> 
      </tr> 
     </thead> 
    </table> 
</div> 

結果:沒有任何警告的彈出窗口,當我點擊表頭。

當我點擊表格的標題時,必須更改什麼來顯示警告對話框?

+2

是否使用任何插件?如果是這樣的話,你需要應用在生成的HTML而不是原始標記... –

+0

我不想觸摸tablesorter插件。爲什麼jQuery .on不能在生成的HTML('table.tablesorter')中工作? –

+0

我剛剛做了一個jsfiddle.net/aakXC/以測試您的代碼,並在測試時在我的示例中顯示一個警告對話框。你的代碼有什麼不同? –

回答

1

如果您正在使用AJAX來加載表,我會推薦一兩件事情:

  1. 只有更新tbody中的行,除非標題單元格被完全替換,那麼你不需要n因此擔心處理標題點擊。

    如果您將表格存儲爲完整表格,則可以按照其他選項(建議#2)或將表格加載到臨時支架中,然後轉移tbody並更新表格。

    var $table = $('#table-content').find('table'); 
    $('#hidden-div').load("ajax.html", function() { 
        // remove old tbody 
        $table.find('tbody').remove(); 
        // move new tbody into the initialized tablesorter table 
        $('#hidden-div').find('table tbody').appendTo($table); 
        // update tablesorter's cache 
        $table.trigger('update'); 
    }); 
    
  2. 如果要更換整個表,只是重新初始化的tablesorter。在Ajax會是這個樣子:

    var options = { /* add tablesorter options here */ }; 
    
    $.ajax({ 
        url: url, 
        data: data, 
        success: function(data){ 
        $('#table-content').find('table').tablesorter(options); 
        }, 
        dataType: dataType 
    }); 
    
+0

改變Ajax行爲的想法解決了這個問題。 –

0

你可以試試這個代碼

$("table.tablesorter tr th.header").click(function() { 
    alert("Handler for .click() called."); 
    }); 
+2

如果您使用的是ajax,不會推薦使用。事件綁定時,該元素可能不存在。 OP使用'.on'正確無誤 –

1
<!DOCTYPE html> 
<html> 
<head> 

<script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
<script> 
$(document).ready(function() { 
$("table.tablesorter tr th.header").click(function() { 
    alert("Handler for .click() called."); 
    }); 
    }); 
</script> 
</head> 

<body> 
<div id="table-content"> 
    <table class="tablesorter"> 
    <thead> 
     <tr> 
      <th class="header">No.</th> 
      <th class="header">Name</th> 
      <th class="header">Phone</th> 
     </tr> 
    </thead> 
</table> 
</div> 

+1

jQuery .click不適用於DOM完成後生成的元素,或者JavaScript創建的元素,如果我們在文檔準備好後調用.click函數一次,就不能使用。 –