【发布时间】:2010-05-20 01:21:49
【问题描述】:
我有一个链接调用ajax加载内容,加载完内容后,我的jquery函数就不起作用了
这是我的 HTML
<a href="#" onclick="javascript:makeRequest('content.html','');">Load Content</a>
<span id="result">
<table id="myTable" valign="top" class="tablesorter">
<thead>
<tr>
<th>Title 1</th>
<th>Level 1</th>
<th>Topics</th>
<th>Resources</th>
</tr>
</thead>
<tbody>
<tr>
<td>Example title 1</td>
<td>Example level 1</td>
</tr>
<tr>
<td>Example title 2</td>
<td>Example level 2</td>
</tr>
</tbody>
</table>
</span>
使用来自http://tablesorter.com/docs/ 的 jquery 表排序器插件对表进行排序 ajax内容加载完毕后,会显示另一组不同数据的表格。但是,排序不再起作用。
这是我用来加载内容的 ajax 脚本:
var http_request = false;
function makeRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url + parameters, true);
http_request.send(null);
}
function alertContents() {
if (http_request.readyState == 4) {
// alert(http_request.status);
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('result').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}
知道如何在内容加载后让 jquery 插件工作吗?
我已经搜索并将 jquery.tablesorter.js 点击函数更改为 live() 像这样$headers.live("click",function(e) 但它也不起作用。
如何让 jquery 函数在内容加载后工作? 谢谢
更新测试脚本:
<a href="#" id="test" onClick="contentDisp()">Load Content</a>
<div id="result"></div>
<script type="text/javascript">
function contentDisp()
{
$.ajax({
url : "test.html",
success : function (data) {
$("#result").html(data);
$("#myTable").tablesorter();
$("#myTable").trigger("update");
}
});
}
</script>
这是我的 test.html。如果我不将其放入已加载的内容中,则表格排序将起作用。一旦它被加载到 div 中,排序就不再起作用了。
<table id="myTable" valign="top" class="tablesorter">
<thead>
<tr>
<th class="header">Title 1</th>
<th class="header">Level 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>Example title 1</td>
<td>Example level 1</td>
</tr>
<tr>
<td>Example title 2</td>
<td>Example level 2</td>
</tr>
</tbody>
</table>
【问题讨论】:
-
当 jQuery 有内置的加载功能,让 http_request 变得更容易时,你为什么还要解决所有的 http_request 麻烦呢? api.jquery.com/load
-
我的链接是动态的,我在分配不同的 div id 时遇到问题,因此我使用了其他 ajax 方法
-
你可以访问像
$("#result")这样的div id。如果您使用 jQuery,您可以在返回数据的上下文中访问 div。我觉得这对你的情况很有用。 -
谢谢,我已经编辑了我的脚本。我意识到它不仅发生在表格排序上,而且也发生在任何其他 jquery 插件上。加载内容后,所有 jquery 插件都无法在新加载的内容中运行。
标签: javascript jquery ajax sorting tablesorter