【问题标题】:jQuery - Changing button in a list of multiple formsjQuery - 更改多个表单列表中的按钮
【发布时间】:2019-01-07 00:11:03
【问题描述】:

我正在开发一个 Spring-Boot 应用程序,我正在尝试根据用户是否喜欢该食谱来更改按钮的图像。

目前,html 获取食谱列表,循环遍历它们并为每个食谱生成一个表单元素和子按钮,因此您最终会得到一个表单列表。所有表单都设置为同一个类,我动态地使按钮 id 不同。

index.html

<div class="grid-100 row addHover" th:each="recipe : ${recipes}">
    <a th:href="@{|/details/${recipe.id}|}">
      <div class="grid-70">
        <p>
        <form class="test" th:action="@{|/recipes/${recipe.id}/favorite|}" method="post" style="display:inline">
          <button  class="favorite-button-index" th:id="'favorite-button-index' + ${recipe.id}">
            <img th:src="${recipe.userFavorites.contains(#authentication.name)} ? @{/assets/images/favorited.svg} : @{/assets/images/favorite.svg}"
                                             style="height: 12px;">
          </button>
        </form>
        <span th:text="${recipe.name}"> </span>

        </p>
     </div>
     </a>

app.js

   $(".test").on("submit", function (e) {
        e.preventDefault();

        $.post(this.action, function (data) {
            console.log(data.favorited)
            var id;
            $('.favorite-button-index').each(function() {
                $(this).click(function(){
                    id = $(this).attr('id');
                    console.log(id)
                    // var imageUrl = (data.favorited) ? '/assets/images/favorited.svg' : '/assets/images/favorite.svg'
                    // $('#id>img').attr('src', imageUrl);
            })

            var imageUrl = (data.favorited) ? '/assets/images/favorited.svg' : '/assets/images/favorite.svg'
            $('#id>img').attr('src', imageUrl);
        });

    });
})

在 app.js 中,当提交单个表单时,我试图在单击时获取子按钮 id,然后使用该 id 来确定应该更改列表中的哪个按钮

data.favorited 产生真/假取决于配方是否已被收藏。

我已经确认 id 变量在单击按钮时通过控制台记录 id 来获取正确的按钮 id,但按钮的图像没有更新。

我对 JS/jQuery 还很陌生,任何帮助都将不胜感激。谢谢!

【问题讨论】:

    标签: javascript jquery spring-boot


    【解决方案1】:

    您可能需要将变量与字符串分开:

     $('#' + id + '>img').attr('src', imageUrl);
    

    您也可以像这样使用string interpolation 使其更干净:

     $(`#${id}>img`).attr('src', imageUrl);
    

    【讨论】:

    • 感谢您的快速回复。您的建议是正确的,我需要将变量分开。我还必须将我的 button.each 事件方法移到表单提交事件方法之外,并将 id 存储在全局范围内。现在,每个食谱的收藏按钮都可以独立工作了。
    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 2016-06-24
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2015-02-02
    相关资源
    最近更新 更多