【问题标题】:How I can get id selector connected with item id如何让 id 选择器与项目 id 连接
【发布时间】:2019-06-19 18:40:35
【问题描述】:

我的应用列表上有按钮列表,其中包含我喜欢的项目。我在这里使用id 选择器。我想使用带有项目 id 的 id 选择器 - 使 id 选择器独一无二。

如何获取项目的 id 并将它们连接到 id 选择器以获得此结果? 1.#voteup-2 2. #voteup-section-2

我正在尝试使用data-id

这是我的 jquery 部分:

        <script type="text/javascript">
            $(document).ready(function(event){
                $(document).on('click', '#voteup', function(event){
                    event.preventDefault();
                    var pk = $(this).attr('value');
                    $.ajax({
                        type: 'POST',
                        url: "{% url 'qa:answer_voteup' %}",
                        data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                        dataType: 'json',
                        success: function(response){
                            $('#voteup-section').html(response['form'])
                            console.log($('#voteup-section').html(response['form']))
                        },
                        error: function(rs, e){
                            console.log(rs.responseText);
                        },
                    });
                });
            });
        </script>

html部分中的按钮,这里我有voteup-section-{{ answer.id }}的id选择器

<div id="voteup-section-{{ answer.id }}" data-id="{{ answer.id }}">
    <form action="{% url 'qa:answer_voteup' %}" method="post">
    {% csrf_token %}
    <button type="submit" id="voteup-{{ answer.id }}" name="answer_id" value="{{ answer.id }}" {% if is_voted_up %} class="btn btn-danger btn-sm">Voted up! {% else %} class="btn btn-primary btn-sm">Vote up!{% endif %} <span class="badge badge-light">{{ answer.total_vote_up }}</span></button>
    </form>
</div>

【问题讨论】:

  • 问题出在客户端,为什么不显示客户端代码?
  • 我想使用带有项目 id 的 id 选择器 - 使 id 选择器独一无二。 这正是您使用基于 id 的选择器的方式。

标签: javascript jquery django list css-selectors


【解决方案1】:

您的意思是希望您的点击处理程序适用于所有这些元素吗?:

<button type="submit" id="voteup-{{ answer.id }}"...

您可以使用starts with selector 捕获id 以已知值开头的所有按钮。像这样的:

$(document).on('click', 'button[id^="voteup-"]', function(event){
    //...
});

这将处理文档中所有&lt;button&gt; 元素的点击,其中它们的id"voteup-" 开头。

【讨论】:

    【解决方案2】:

    另一种选择是为按钮分配一个类。

    <button ... class="btn btn-danger btn-sm btn-vote" ...>Vote up!</button>
    

    我已将按钮 HTML 简化为仅用于说明这一点的类。 “btn-vote”类可以是您选择的任何内容。 jQuery 选择器就变成了

    $(document).on('click', 'button.btn-vote', function(event){
        //...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-01
      • 2011-01-02
      • 2012-02-15
      • 2011-02-08
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多