首页 > 解决方案 > 如何在 JQuery 中使用每个并在 html 表中显示

问题描述

当前的问题是我的电影标题的完整列表显示在我表的第一行中。我要他们分开。我需要以某种方式将它们分解成单独的元素,但我似乎找不到任何好的例子来工作。(仅供参考,我是 JavaScript/JQuery 的新手)

<body>

    <table id="content">
        <tr>
            <td></td>
        </tr>
    </table>

    <form>
        TITLE:<br>
        <input type="text" id="inputTitle" value="" placeholder="Title"><br>
        RELEASE DATE:<br>
        <input type="text" id="inputRelease" value="" placeholder="Release"><br>
        DIRECTOR:<br>
        <input type="text" id="inputDirector" value="" placeholder="Director"><br>
        GENRE:<br>
        <input type="text" id="inputGenre" value="" placeholder="Genre"><br>
    </form>   
    <br><br>
    <button id='button'>Add Movie</button>

<script>

$(document).ready(function(){

    $.get("https://moviesfrontandback.herokuapp.com/api/movies/", function(data){
        var i;
        for (i = 0; i < data.length; i++) {
            $('#content').append(data[i].title)    
        }
    });

    $('#button').click(function(){
        title = $('#inputTitle').val()
        releaseYear = $('#inputRelease').val()
        director = $('#inputDirector').val()
        genre = $('#inputGenre').val()
        WriteToAPI()
    })

    WriteToAPI = function(){
        $.post('https://moviesfrontandback.herokuapp.com/api/movies/', {
            title: title,
            releaseYear: releaseYear,
            director: director,
            genre: genre,
        }, function(data, status){
            alert("Title:\t\t" + title + "\nRelease:\t" + releaseYear + "\nDirector:\t" + director + "\nGenre:\t\t" + genre)
        } )
    }

    });

</script>

</body>
</html>

标签: jqueryforeachhtml-table

解决方案


您需要为表格设置 html,而不仅仅是附加标题。像这样的东西...

$.get("https://moviesfrontandback.herokuapp.com/api/movies/", function(data){
    var html = '';
    for (var i = 0; i < data.length; i++) {
        //Append a new row
        html += '<tr><td>' + data[i].title + '</td></tr>'    
    }
    //Overwrite the table html
    $('#content').html(html);
});

推荐阅读