所以我写了一个函数,它可以根据json数据库为我创建一个网页,现在我想添加两个函数:
1:如果你点击like img(它得到id按钮),网页上的like计数器应该增加1。 很简单,只需点击jqery变量++,然后。text(变量)2:一个排序函数--基于收到的喜欢一个项目,你应该能够对它进行排序(最喜欢的div第一,第二,第三。。。。
当我给出所有的like按钮并输出一个单独的id时,我可以为每个单独的变量编写它,但是我希望它是动态的,所以如果你向json文件中添加新的数据,它可以动态地与like和sort函数一起工作。 这类人现在还没有安全的地方。
自从我在上面花了3个小时和谷歌那么多,那么多的堆栈溢出,我想我的大脑被不同的东西超负荷了,现在似乎没有什么能工作^^
--
function filmInsert(insert) {
$.each(film, function(i, data) { //.each statt loop
let box =
`<div class="boxwrapper">
<div class="imgbox">
<img src="${data.img}" alt="${data.titel}">
</div>
<div class="textbox">
<h3>${data.titel}</h3>
<p>${data.beschreibung}</p>
<p> <a id="button${data.id}">
<img src="img/budspencer_official.png"> Like
</a>
<span class="output${data.id}">${data.likes}</span>
</p>
</div>
</div>`;
insert.append(box);
});
}
我为BoxWrapper
项添加了一个容器元素,因为我假设您有一个容器元素,而且最好有一个容器元素,而不是仅仅将已排序的项添加到HTML文档的正文中。
null
$(document).on("click", ".textbox a", function() {
let likes = parseInt($(this).closest(".textbox").find("span").text());
$(this).closest(".textbox").find("span").text(likes + 1);
});
$("#sort").on("click", function() {
let divs = $(".boxwrapper")
let sorted = divs.sort(function(a, b) {
return $(a).find("span").text() < $(b).find("span").text();
});
$(".container").html(sorted);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel</h3>
<p>Description</p>
<p> <a id="button1">
<img src="https://dummyimage.com/40x40/000/fff&text=1"> Like
</a>
<span class="output1">0</span>
</p>
</div>
</div>
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel 2</h3>
<p>Description 2</p>
<p> <a id="button2">
<img src="https://dummyimage.com/40x40/000/fff&text=2"> Like
</a>
<span class="output2">0</span>
</p>
</div>
</div>
</div>
<button id="sort">
Sort
</button>