我在这里有这个div:
<div id='suggested_students'>
</div>
我正在尝试编写一些javascript,它会使用正确的值附加它:
<div id='STUDENT NAME' onClick='moveProfile("STUDENT NAME", "STUDENT ID")'>
STUDENT NAME<br>
STUDENT ID<br>
</div>
这是我的javascript / ajax:
$('#search_bar').keyup(function () {
var keyword = $('#search_bar').val();
if(keyword.length > 2){
console.log('hey')
var url = window.location.pathname;
$.ajax({
method: 'GET',
url: url,
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
var suggestions = data.students;
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
console.log(current_student[0])
console.log(current_student[1])
}
}
});
}
})
并且for循环的每次迭代产生类似于:
的东西 [STUDENT NAME, STUDENT ID
如何填写这些占位符,然后将html附加到每个学生的主要部分。
答案 0 :(得分:1)
这会将学生信息添加到容器div中......
success: function (data) {
// get a reference to the container div
var $container = $("#suggested_students");
// remove any existing student information
$container.empty();
var suggestions = data.students;
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
// create a new div to add to the container element
var $div = $("<div/>");
$div.data("name", current_student[0]);
$div.data("id", current_student[1]);
$div.html(current_student[0] + "<br/>" + current_student[1]);
$div.on("click", moveProfile);
$container.append($div);
}
}
这里有一些值得注意的事情。首先,我没有给每个新div提供学生姓名的ID。这有几个原因,但主要原因是它不是一个非常友好的ID。名称有空格,也可以有其他标点符号。此外,您可以让多个学生使用相同的名称,但您不能拥有多个具有相同ID的元素。
其次,我为每个学生div设置数据属性,而不是在内联事件处理程序中传递值。要处理点击事件,您需要这个额外的功能,已在上面引用...
function moveProfile() {
var $this = $(this);
var studentId = $this.data("id");
var studentName = $this.data("name");
// do whatever you need with the student info here
}
答案 1 :(得分:0)
试试这个:
$('#search_bar').keyup(function () {
var keyword = $(this).val(), $suggested_students;
$suggested_students = $('#suggested_students');
if (keyword.length > 2) {
var url = window.location.pathname;
$.ajax({
method: 'GET',
url: url,
data: {
'keyword': keyword
},
dataType: 'json',
success: function (data) {
var i, suggestions, s_name, s_id, current_student;
suggestions = data.students;
// empty before
$suggested_students.empty();
for(i = 0; i< suggestions.length; i++){
current_student = suggestions[i];
s_id = current_student[0];
s_name = current_student[1]
$suggested_students.append(
"<div id='" + s_id + "' onClick='moveProfile(\"" + s_name + "\", \"" + s_id +"\")'>" +
s_id + " <br>" +
s_name + " <br>" +
"</div>"
);
}
}
});
}
});
然而,我建议在写入新字符串时中止$.ajax
调用,或者在执行新字符串之前等待片刻并避免以这种方式使用onClick
:只需添加一个类或者像#suggested_students > div
这样的选择器,并为容器内的每个click
添加一个div
事件监听器。
答案 2 :(得分:-1)
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
console.log(current_student[0])
console.log(current_student[1])
var div = "<div id='"+current_student[0]+"' onClick='moveProfile(\""+current_student[0]+"\", "+current_student[1]+")'>"+current_student[0]+"<br>"+current_student[1]+"<br></div>";
$('#suggested_students').append(div);
}