[英]jQuery action on Ajax ResponseText object
好吧,我对jQuery完全陌生,可能这里缺少一些明显的东西……我想做的是:
1)使用JavaScript + Ajax + PHP通过ResponseText从MySQL数据库中提取表(当前有效)
2)使用jQuery对表执行操作(不起作用)
代码的第一部分(1)如下所示:
<script>
function displayPeople(String) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("People").innerHTML=xmlhttp.responseText;
}
}
var Query = "?String=" + String;
xmlhttp.open("GET","library/display_people.php"+Query,true);
xmlhttp.send();
}
window.onload = displayPeople("");
</script>
<input id="Search_People" placeholder="Search People by Name" size="50" onkeyup="displayTable(this.value)">
<div id="People" style="width:900px; height:200px; overflow-y:scroll;">
当用户在输入字段中输入名称时,该表将动态更新。 PHP文件组装查询并返回:
$display_string = "<table>";
while($row = mysqli_fetch_array($Results)){
$display_string .= "<tr>";
$display_string .= "<td>" . $row['FirstName'] . "</td>";
$display_string .= "<td>" . $row['LastName'] . "</td>";
$display_string .= "<td>" . "<button class='editbtn'>edit</button>" . "</td>";
$display_string .= "</tr>";
}
$display_string .= "</table>";
echo $display_string;
现在 ,第(2)部分,我想在表条目上使用jQuery执行一些操作(最终目标是: http : //www.9lessons.info/2011/04/live-table-edit-delete-with -pagination.html )。
首先,我将此jQuery脚本添加到了另一个教程( http://jsfiddle.net/tXS6w/ )中的.html中,该教程对任何“静态”表都适用,但是对上表没有任何作用! 也就是说,如果我单击应该更改标签的按钮,则什么也不会发生...
$(document).ready(function () {
$('.editbtn').click(function () {
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
我该如何进行这项工作?
我对JavaScript / Ajax / PHP的了解非常有限,因此,最简单的解决方案受到欢迎!
谢谢!!!
尝试这样的事情
$('#People').on('click','.editbtn',function () {
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
原因:
您可以正确地编写代码,因为DOM中已经存在表,因此可以对其进行click事件。
但是它不适用于动态添加到DOM的元素,因为您必须使用jQuery Delegate
或On
函数。
delegate()
http://api.jquery.com/on/
类.editbtn
的按钮尚不在document.ready的DOM中,因为您稍后会加载表内容。 在ajax请求完成之后,您必须将click事件添加到按钮中。
该edit
按钮是动态生成所以单击事件不会工作,因为它是委托的事件,所以使用.on
代替.click
代替
$(document).ready(function () {
$('.editbtn').click(function () {
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
用这种方式
$(document).ready(function () {
$(document).on.('click','.editbtn',function () {
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
现在这应该可以按照您的预期工作。
有关委托事件的更多信息,请参见: http : //api.jquery.com/on/
我已经修改了您的jsfiddle以展示委托事件,您可以检查一下。
现场演示:
http://jsfiddle.net/dreamweiver/tXS6w/291/
快乐编码:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.