【问题标题】:separate divs with same class name from each other将具有相同类名的 div 彼此分开
【发布时间】:2017-05-01 16:40:51
【问题描述】:

如何区分具有相同类名的 div?我有这样的事情:

    <form role="form" id="comment-form">
      <textarea class="form-control" rows="1" placeholder="{% trans 'Write a comment...' %}" name="comment" id="comment"></textarea>
  </form>

    <form role="form" id="comment-form">
      <textarea class="form-control" rows="1" placeholder="{% trans 'Write a comment...' %}" name="comment" id="comment"></textarea>
  </form>

    <form role="form" id="comment-form">
      <textarea class="form-control" rows="1" placeholder="{% trans 'Write a comment...' %}" name="comment" id="comment"></textarea>
  </form>

    ...

我想添加这个:

$("#comment").keydown(function (evt) {
    var keyCode = evt.which?evt.which:evt.keyCode;
    if (evt.ctrlKey && (keyCode == 10 || keyCode == 13)) {
      $.ajax({
        url: '/articles/comment/',
        data: $("#comment-form").serialize(),
        cache: false,
        type: 'post',

但是在 keydown 上只有第一个 id="comment" 的 textarea 响应,因为每个元素都必须有 unice id。我尝试将它们更改为类,但随后它们都会响应。我怎样才能将这种形式与进入彼此的方式分开?

【问题讨论】:

  • ID 是唯一标识符。不要使用多个相同的。这就像我给两个人一个名为“麦当劳叔叔”的身份证,并告诉你和麦当劳叔叔握手,但不是你想要的,我想要的。
  • 这是一个 html/id 问题,您发布的 html 中没有 #comment-list
  • 好吧,如果不给他们 id,我该怎么做?

标签: javascript html css django


【解决方案1】:

您需要将 id 更改为 classes,这样您就不会重复 id,然后当您定位 .comment-form、'.comment' 等时,您需要在每个块中引用相对类。

$(".comment").keydown(function (evt) {
    var keyCode = evt.which?evt.which:evt.keyCode;
    if (evt.ctrlKey && (keyCode == 10 || keyCode == 13)) {
      var $commentForm = $(this).closest(".comment-form"),
          $comment = $(this);
      $.ajax({
        url: '/articles/comment/',
        data: $commentForm.serialize(),
        cache: false,
        type: 'post',
        success: function (data) {
          /* comment-list and comment-count aren't in your html...
          $("#comment-list").html(data);
          var comment_count = $("#comment-list .comment").length; 
          $(".comment-count").text(comment_count);
          */
          $comment.val("");
          $comment.blur();
        }
      });
    }
});
<form role="form" class="comment-form">
  <textarea class="form-control comment" rows="1" placeholder="{% trans 'Write a comment...' %}" name="comment"></textarea>
</form>

<form role="form" class="comment-form">
  <textarea class="form-control comment" rows="1" placeholder="{% trans 'Write a comment...' %}" name="comment"></textarea>
</form>

<form role="form" class="comment-form">
  <textarea class="form-control comment" rows="1" placeholder="{% trans 'Write a comment...' %}" name="comment"></textarea>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    相关资源
    最近更新 更多