[英]Trying to select li element with JQuery
我希望用JQuery获取开始和结束LI标签之间的文本/数据。 以下是我正在使用的代码。 现在的页面将根据我在表单中键入的内容异步出去查询数据库。 我希望能够点击LI项目并将其放在标有#in_attendance的div中。 在此先感谢您的所有帮助。
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#search').keyup( function() {
var item = $('#search').val();
var html = "";
$.post("./search/attend", { 'search' : item },
function(data){
for(i=0; i<data.bro.length; i++){
options = data.bro[i].first_name, " ", data.bro[i].last_name;
html = html.concat("<li value='", options, "'>", data.bro[i].first_name," ",data.bro[i].last_name,"</li>");
}
document.getElementById('selections').innerHTML = html;
},
"json");
});
$("#selections li").click(function() {
alert($(this).text());
});
});
</script>
</head>
<title></title>
<body>
<?php
echo form_open('search/attend');
echo form_input(array('name' => 'search', 'id' => 'search', 'autocomplete' => 'off'));
echo form_close();
?>
<ul id="selections">
</ul>
<hr />
<div id="in_attendance">
</div>
</body>
你遇到的问题是你的clcik处理程序不会绑定到未来的元素。 使用on()方法将事件附加到永久在页面中的父项,并通过传入要处理元素“li”作为第二个参数的选择器,clcik将仅在“li”上注册
$("#selections").on('click','li',function() {
alert($(this).text());
});
除了使用.on()
,您还可以将单击处理程序移动到$.post()
完成事件:
$(document).ready(function() {
$('#search').keyup( function() {
var item = $('#search').val();
var html = "";
$.post("./search/attend", { 'search' : item },
function(data){
for(i=0; i<data.bro.length; i++){
options = data.bro[i].first_name, " ", data.bro[i].last_name;
html = html.concat("<li value='", options, "'>", data.bro[i].first_name," ",data.bro[i].last_name,"</li>");
}
document.getElementById('selections').innerHTML = html;
$("#selections li").click(function() {
alert($(this).text());
});
},
"json");
});
});
您需要保持活动绑定。 见下面的样本。
$('#selections li').live('click', function() {
alert($(this).text());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.