我有一种情况,我正在对数据库进行ajax调用,并返回数据。数据以表格格式进入div,我希望这些行可以点击。这是一个简单的过程,每天在网上完成数十亿次(通过姓氏部分匹配查找数据库中的人)。
在项目的其他五个页面上,从数据库中读取信息,将其发布到屏幕上,然后单击行以重定向到新页面是没有问题的。不同的是,这些页面是用PHP在页面上编写的。这个特定页面必须用javascript编写,因为我要求用户输入姓氏中的一个或两个字母,进行ajax调用并填充div。
以下是调用和写入数据的代码:
$.ajax({
type: "POST",
url: "findpatientbackend.php",
data: {letterslastname: lastname},
dataType : 'json',
success: function(result) {
$("#div1").html(""); //make the div blank
if(result.length >= 1)
{var output = "";
$("div1").html("<table id='findtable'>");
$.each(result, function(index, value) {
output += "<tr><td width='100px'></td><td id='localid' width='100px'>"
+ value.localid + "</td><td width='100px'>"
+ value.lastname + "</td><td width='100px'>"
+ value.firstname + "</td><td width='100px'>"
+ value.middlename + "</td><td width='100px'>"
+ value.dob + "</td></tr>";
});
$("#div1").html(output);
$("div1").html("</table>");
}
else
{$("#div1").html("No matches");}
},
error : function() { alert("error on return"); }
});
});
这里是“点击”行的代码(在其他五种情况下可以正常工作):
$("#findtable tr").click(function() {
var passthis = $(this).find("#localid").html();
$.post("php/setsessionvariable.php",
{sessionval: passthis},
function(e) {window.location.href = '../root.php'}
);
我已经玩过这玩了,好像.click函数看不到'id ='findtable'',我已经尝试了一切 - 从id改为class,单引号,双引号,移动位置和 - 我能想到的一切。当我使用IE执行“查看源代码”时,我会看到除了表和数据之外的所有内容,但表格和数据在屏幕上是清晰的。
这很重要,只是为了帮助项目,但对我来说理解正在发生的事情更为重要。例如,有什么基本的东西:
昨天我了解了jQuery dataTables库(以及其他许多),这可能会为我提供一个不同的途径,但我宁愿在这段代码中了解这个问题。
(P.S.再次感谢@Shaddow帮助我使用.each命令 - 非常好!)
这是细分:
$(document).on(
"click",
"#findtable td",
(function() {
var passthis = $(this).find("#localid").html();
$.post("php/setsessionvariable.pphp",
{sessionval: passthis},
function(e) { window.location.href = '../root.php'; }
);
});
);
以下是纯Javascript表的代码,它实际上允许.click函数工作。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" type="text/javascript"></script>
<style>
#findtable {
width:200px;
background-color:#CFD3FE;
margin:10px auto;
text-align:center;}
</style>
<body>
<div id="puttablehere"></div>
<script>
$(document).ready(function () {
var output = "<table id='findtable'>";
for (var i = 0; i<38; i++)
{output += "<tr><td width='100px'>X</td><td id='localid' width='100px'>X</td></tr>";}
output += "</table>";
$("#puttablehere").html(output);
$("#findtable tr").click(function(e) { alert("it works!"); });
});
</script>
</body>
</html>
由于您的表是动态添加的,因此您需要为事件使用事件委派。您将处理程序绑定到DOM准备就绪的元素:
$(document).on("click", "#findtable td", function() {
var passthis = $(this).find("#localid").html();
$.post("php/setsessionvariable.php", {sessionval: passthis}, function(e) {
window.location.href = '../root.php'; //I removed the } from here.
});
});