简体   繁体   English

在变量内定义动态输出?

[英]Define a dynamic output inside a variable?

I hope the title is not wrongfully put or misleading. 我希望标题不会被错误放置或误导。 What I want to do, in order to cut down unnecessary repetition of code, is something like this: 为了减少不必要的代码重复,我想做的事情是这样的:

const predefinedOutput = "for(let i = 0; i < movie.length; i++) {
    output += `<div class="card">
    <div class="overlay">
    <div class="movie">
        <h2>${movie[i].title}</h2>
            <p><strong>Rating:</strong> ${movie[i].vote_average}</p>
            <p><strong>Release date:</strong> ${movie[i].release_date}</p>
            <a onclick="movieSelected('${movie[i].id}')" href="#">Details</a>
     </div>
    </div>
    <div class="card_img">
        <img src="http://image.tmdb.org/t/p/w300/${movie[i].poster_path}" onerror="this.onerror=null;this.src='../images/imageNotFound.png';">
    </div>
    </div>`;
};

How can I, if its doable at all, to sort of pre-define an output that includes a forloop, that will be then used in an API call, so I don't make duplicates of the code above for different searches (page change, genre change etc.)? 如果完全可行,我如何才能对包含forloop的输出进行预定义,然后将其用于API调用中,因此我不会在上面的代码中重复用于不同的搜索(页面更改) ,类型变更等)? Thanks in advance. 提前致谢。

Try the following example. 请尝试以下示例。 Don't know what movies is so had to make something of it. 不知道要拍什么电影。 In this example it should be an array. 在此示例中,它应该是一个数组。 You could also use .map() but then the movies should be an object. 您也可以使用.map()但是movies应该是一个对象。 map and forEach do the same as a for loop mapforEachfor循环相同

<script>
movies.forEach( movie => {
    output += `<div class="card">
                    <div class="overlay">
                        <div class="movie">
                            <h2>${movie.title}</h2>
                                <p><strong>Rating:</strong> ${movie.vote_average}</p>
                                <p><strong>Release date:</strong> ${movie.release_date}</p>
                                <a onclick="movieSelected('${movie.id}')" href="#">Details</a>
                        </div>
                    </div>
                    <div class="card_img">
                        <img src="http://image.tmdb.org/t/p/w300/${movie.poster_path}" onerror="this.onerror=null;this.src='../images/imageNotFound.png';">
                    </div>
                </div>`;
});

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

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