【问题标题】:How to get a unique modal header for each stock?如何为每只股票获得一个独特的模态标题?
【发布时间】:2018-02-04 22:43:32
【问题描述】:

我正在尝试创建一个虚拟股票市场,在其中我有不同的模式来显示有关每只股票的信息。 但是模板呈现为这样,我无法为每只股票获得唯一的模态标题。

即使在单击“CIPLA”股票后,我也会将“购买 HDFC”作为模态标题。 这是我的 django 模板。

    {% for stock in user.stocks.all %}
    <li class="list-group-item">
        <b>{{ stock.stock_name  }}</b>
        <p id="curr">Current price : {{ stock.current_price }}</p>
        Bought at : {{ stock.buy_price }}
        <button class="btn" id="buy" data-toggle="modal" data-target="#buy-modal">Buy</button>
        <!--Modal for buy-->
        <div id="buy-modal" class="modal fade" role="dialog">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Buy {{ stock.stock_name }}</h4>
                  </div>
                  <div class="modal-body">
                      <form method="post" action="/stocks/{{ user.id }}/{{ stock.stock_name }}/buy/" >
                          {% csrf_token %}
                        <label for="quantity">Quantity</label>
                        <input type="number" id="quantity-buy" name="quantity">
                        <button class="btn" id="confirm-buy" type="submit" >Buy</button>
                      </form>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                  </div>
                </div>

            </div>
        </div>

我用{% endfor %}结束了它。

【问题讨论】:

    标签: html django twitter-bootstrap django-templates


    【解决方案1】:

    错误是由这一行引起的:

    <button class="btn" id="buy" data-toggle="modal" data-target="#buy-modal">Buy</button>
    

    如您所见,这条线被映射到 data-target="#buy-modal" 。这意味着带有id="buy-modal" 的Dom 元素会被它调用。

    现在,如果您查看代码内部,您将创建多个模式(但使用相同的 html id)。

    根错误是具有相同 id 的多个 Dom 元素。如果你看这一行:

    <div id="buy-modal" class="modal fade" role="dialog">
    

    这条线在你的 Dom 中被创建了 n 次(因为它在一个循环中运行)。这意味着存在具有相同 ID 的 n-模态。这也意味着你的 Dom 有 n 个模态 具有相同的 id

    现在这是编写 html 的错误做法。

    每次点击按钮:

    <button class="btn" id="buy" data-toggle="modal" data-target="#buy-modal">Buy</button>
    

    html 解析器在您的 html 中查找相应的 data-target。这显然是 n(因为您创建了 n;超过 1)。现在 html 每次都会调用第一个或任何特定的模态,因为它在初始化模态时只解析一个。 因此每次单击按钮时,都会弹出相同的模式

    因此,要解决此问题,您必须创建具有不同 id 和不同按钮触发器的模式

    希望这会有所帮助。谢谢。

    【讨论】:

    • 很抱歉来不及接受这个答案。我花了很长时间才明白你想说什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多