简体   繁体   English

如何使用变量Javascript将div附加到div中

[英]How to append a div into a div with variables Javascript

I have this div here: 我在这里有这个股利:

<div id='suggested_students'>

</div>

I am trying to write some javascript which will append this with the correct values: 我正在尝试编写一些javascript,将其附加正确的值:

<div id='STUDENT NAME' onClick='moveProfile("STUDENT NAME", "STUDENT ID")'>
STUDENT NAME<br>
STUDENT ID<br>
</div>

This is the javascript/ajax I have: 这是我拥有的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])

                }
            }
            });
    }
})

and each iteration of the for loops produces something like: for循环的每次迭代都会产生如下结果:

[STUDENT NAME, STUDENT ID

How do I go about filling in these place holders and then appending the html to the main div for each student. 我该如何填写这些占位符,然后将html附加到每个学生的主要div上。

This will add the student information into the container div for you... 这会将学生信息添加到您的容器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);
    }
}

There's a couple of things worth noting here. 这里有两点值得注意。 Firstly, I didn't give each new div the ID of the student name. 首先,我没有给每个新的div学生姓名的ID。 There are several reasons for this, but the main one is that it's not a very friendly ID. 造成这种情况的原因有很多,但主要的原因是它不是一个非常友好的ID。 Names have spaces and can also have other punctuation marks. 名称有空格,也可以有其他标点符号。 Also, you can have multiple students with the same name, but you can't have multiple elements with the same ID. 同样,您可以有多个具有相同名称的学生,但不能有多个具有相同ID的元素。

Secondly, I set data attributes for each student div, rather than pass the values in an inline event handler. 其次,我为每个学生div设置数据属性,而不是在嵌入式事件处理程序中传递值。 To handle the click event you'd need this extra function, already referenced above... 要处理click事件,您需要此额外功能,上面已经提到了...

function moveProfile() {
    var $this = $(this);
    var studentId = $this.data("id");
    var studentName = $this.data("name");

    // do whatever you need with the student info here
}

Try this: 尝试这个:

$('#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>"
                    );
                }
            }
        });
    }
});

I suggest, however, to abort the $.ajax call in case a new string is written or wait a few moments before executing a new one and avoid using onClick in this way: just add a class or a selector like #suggested_students > div and add a click event listener to each div inside the container. 但是,我建议中止$.ajax调用,以防万一写入新字符串,或者在执行新字符串之前稍等片刻,并避免以这种方式使用onClick :只需添加类或选择器,例如#suggested_students > div和向容器内的每个div添加一个click事件监听器。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM