向现有动态功能添加“赞 + 排序”函数

我编写了一个函数,该函数基于 json 数据库为我动态创建网页。

现在我想添加2个函数:

  1. 如果您单击喜欢img(它获得了id按钮),则网页上的喜欢计数器应增加1。非常简单,只需使用jQuery变量++进行一次(单击),然后.text(variable)

  2. 排序函数 - 基于喜欢的一个项目收到,你应该能够排序它(最喜欢的div第一,第二,第三....

当我给所有喜欢的按钮并输出一个单独的ID时,我可以为每个单独的变量单独编写它,但我想让它成为动态的,所以如果你将新数据添加到json文件,它可以动态地与喜欢和排序函数一起工作。

喜欢的人现在没有保存在任何地方。

自从坐在上面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);

    });

  }


森栏
浏览 105回答 1
1回答

繁花如伊

我已经为项目添加了一个容器元素,因为我假设你有一个,因为最好有一个,而不仅仅是将排序的项目添加到HTML文档的正文中。boxwrapper$(document).on("click", ".textbox a", function() {&nbsp; let likes = parseInt($(this).closest(".textbox").find("span").text());&nbsp; $(this).closest(".textbox").find("span").text(likes + 1);});$("#sort").on("click", function() {&nbsp; let divs = $(".boxwrapper")&nbsp; let sorted = divs.sort(function(a, b) {&nbsp; &nbsp; &nbsp;return $(a).find("span").text() < $(b).find("span").text() ? 1 : -1;&nbsp; });&nbsp; $(".container").html(sorted);});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="container">&nbsp; <div class="boxwrapper">&nbsp; &nbsp; <div class="imgbox">&nbsp; &nbsp; &nbsp; <img src="example.gif" alt="Title">&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="textbox">&nbsp; &nbsp; &nbsp; <h3>Titel</h3>&nbsp; &nbsp; &nbsp; <p>Description</p>&nbsp; &nbsp; &nbsp; <p> <a id="button1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img src="https://dummyimage.com/40x40/000/fff&text=1"> Like&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; &nbsp; <span class="output1">0</span>&nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; </div>&nbsp; </div>&nbsp; <div class="boxwrapper">&nbsp; &nbsp; <div class="imgbox">&nbsp; &nbsp; &nbsp; <img src="example.gif" alt="Title">&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="textbox">&nbsp; &nbsp; &nbsp; <h3>Titel 2</h3>&nbsp; &nbsp; &nbsp; <p>Description 2</p>&nbsp; &nbsp; &nbsp; <p> <a id="button2">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img src="https://dummyimage.com/40x40/000/fff&text=2"> Like&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; &nbsp; <span class="output2">0</span>&nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; </div>&nbsp; </div></div><button id="sort">&nbsp; Sort</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript