【问题标题】:jQuery selector is wrong on removeAttrjQuery 选择器在 removeAttr 上是错误的
【发布时间】:2022-01-23 11:47:09
【问题描述】:

我尝试从某个类中删除所有ids,然后将id 放在click 上的一个新元素上,该元素有一个类但它不起作用。

添加新的id 似乎有效,但在添加新的id 之前删除所有ids 无效。

这是我的代码:

$(".response").click(function () {
//    $('.responsediv').find("input[type=text], textarea").val("");
    $('.blogcommentresponse-form').removeAttr('id')
    $(".responsediv").fadeOut();
    $(this).parents("div").next(".responsediv").css("visibility", "").fadeIn(100);
    $(this).parents("div").next(".responsediv").closest(".blogcommentresponse-form").attr('id','blogcommentresponse-form');
});

它适用于将id 添加到新表单元素,但不适用于删除所有其他表单的id

也许我认为单击功能不适用于此选择器之外的类的选择器。

应该在我的博客上应用的代码:

<div class="comments">
  <div class="u-heading-v3-1 g-mb-5">
    <h2 class="h3 u-heading-v3__title g-brd-primary  no-padding-b">
      Commentaires sur cet article
    </h2>
  </div>
  <div class="media g-mb-20"> <img loading="lazy" class="d-flex g-width-60 g-height-60 rounded-circle g-mt-3 g-mr-20" src="assets/img/team/face-6.png" alt="">
    <div class="media-body u-shadow-v22 g-bg-secondary g-rounded-5 g-pa-10">
      <div class="d-flex align-items-start g-mb-15 g-mb-10--sm">
        <div class="d-block">
          <h5 class="h6 g-color-black g-font-weight-600">Gérard Ricard</h5> <span class="d-block g-color-gray-dark-v5 g-font-size-11">15 janvier 2022 à 00:05</span>
        </div>
        <div class="ml-auto"> <a class="u-link-v5 g-color-black g-color-blue--hover g-font-weight-600 g-font-size-12 text-uppercase response" style="cursor:pointer">Répondre</a> </div>
      </div>
      <p>Bonjour, que préconisez-vous pour le renforcement de vieux murs en bauges ?
        Par avance merci </p>
      <ul class="list-inline my-0 pull-right">
        <li class="list-inline-item rating">
          Note :
          <i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i><i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i><i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i><i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i><i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i>
        </li>
      </ul>
    </div>
  </div>
  <div class="responsediv row" style="display:none">
    <div class="col-md-2 text-left"></div>
    <div class="respondform col-md-9">
      <div class="u-heading-v3-1 g-mb-5">
        <h3 class="h3 u-heading-v3__title g-brd-primary  no-padding-b">
          Publier une réponse au commentaire de Gérard Ricard
        </h3>
      </div>
      <form action="plugins/skyforms/blog-comment-response-process.php" method="post" class="blogcommentresponse-form sky-form comment-style" novalidate="novalidate"> <input type="hidden" name="id_article" value="103"> <input type="hidden" name="face_id" value="4"> <input type="hidden" name="id_comment" value="119">
        <fieldset>
          <div class="row">
            <div class="bon_blog_commentresponse_box form-group col-lg-6 g-mb-10"> <input type="hidden" name="blogcommentresponse"> <label class="g-mb-10" for="bon_blog_commentresponse_name">Votre nom :</label> <input class="form-control g-bg-gray-light-v5 g-bg-gray-light-v5--focus g-brd-gray-light-v5 g-rounded-1 g-pa-10" placeholder="Nom ou Pseudo" type="text" name="nom_blog_commentresponse" required=""> </div>
            <div class="bon_blog_commentresponse_box form-group col-lg-6 g-mb-10"> <label class="g-mb-10" for="bon_blog_commentresponse_email">Votre e-mail :</label> <input class="form-control g-bg-gray-light-v5 g-bg-gray-light-v5--focus g-brd-gray-light-v5 g-rounded-1 g-pa-10" placeholder="Adresse e-mail" type="email" name="email_blog_commentresponse" required=""> </div>
          </div>
          <div class="form-group g-mb-20"> <label class="g-mb-5" for="commentaire_blog_commentresponse">Votre commentaire :</label> <textarea class="countit form-control rounded-0 form-control-md w-100 faq-form g-bg-gray-light-v5 g-bg-gray-light-v5--focus g-brd-gray-light-v5 g-rounded-1 g-pa-10" name="commentaire_blog_commentresponse" rows="5" placeholder="Tapez votre commentaire ici" minlength="30" maxlength="500" required=""></textarea>
            Caractères restant : <span class="counter_desc">500 caractères</span> </div>
          <p><button type="submit" class="btn w-100 u-btn-primary text-center"><i class="fa fa-send"></i> Envoyer votre commentaire</button></p>
        </fieldset>
      </form>
      <div class="row">
        <div class="bon-blogcommentresponse-success g-mb-20"></div>
        <div class="message-blogcommentresponse message alert alert-dismissible fade show g-bg-teal g-color-white rounded-0 w-100" role="alert"> <button type="button" class="close u-alert-close--light" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
          <div class="media"> <span class="d-flex g-mr-10 g-mt-5"> <i class="icon-check g-font-size-25"></i> </span> <span class="media-body align-self-center"> <strong>Terminé !</strong> Votre réponse a bien été envoyée. Elle est en attente de modération.
            </span> </div>
        </div>
        <div class="error-blogcommentresponse message error alert alert-dismissible fade show g-bg-yellow rounded-0 w-100" role="alert"> <button type="button" class="close u-alert-close--light" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
          <div class="media"> <span class="d-flex g-mr-10 g-mt-5"> <i class="icon-info g-font-size-25"></i> </span> <span class="media-body align-self-center"> <strong>Attention !</strong> A cause d'une erreur technique, le commentaire n'a pas pu être envoyé. Veuillez recommencer plus tard.
            </span> </div>
        </div>
      </div>
    </div>
    <div class="col-md-1 text-left"><br> <span style="cursor:pointer ;color:#000000 !important" class="annulereponse">X</span> </div>
  </div>
  <div class="media  g-brd-gray-light-v4 g-ml-40 g-mb-30"> <img loading="lazy" class="d-flex g-width-60 g-height-60 rounded-circle g-mt-3 g-mr-15" src="assets/img/team/face-99.png" alt="">
    <div class="media-body u-shadow-v22 g-bg-secondary g-rounded-5 g-pa-10">
      <div class="d-flex align-items-start g-mb-15 g-mb-10--sm">
        <div class="d-block">
          <h5 class="h6 g-color-black g-font-weight-600">Stan Piotrowski</h5> <span class="d-block g-color-gray-dark-v5 g-font-size-11">16 janvier 2022 à 21:27</span>
        </div>
      </div>
      <p>Bonjour,
        l'idéal est d'utiliser des croix de chaînages reliées avec des tirants. Toutefois vous pouvez aussi réaliser un chaînage traditionnel avec une structure armée. Veillez a bien utiliser un mortier de scellement à retrait compensé afin de s'adapter aux propriétés de dilatation de la terre.</p>
    </div>
  </div>
  <div class="media g-mb-20"> <img loading="lazy" class="d-flex g-width-60 g-height-60 rounded-circle g-mt-3 g-mr-20" src="assets/img/team/face-5.png" alt="">
    <div class="media-body u-shadow-v22 g-bg-secondary g-rounded-5 g-pa-10">
      <div class="d-flex align-items-start g-mb-15 g-mb-10--sm">
        <div class="d-block">
          <h5 class="h6 g-color-black g-font-weight-600">Smith</h5> <span class="d-block g-color-gray-dark-v5 g-font-size-11">14 janvier 2022 à 08:02</span>
        </div>
        <div class="ml-auto"> <a class="u-link-v5 g-color-black g-color-blue--hover g-font-weight-600 g-font-size-12 text-uppercase response" style="cursor:pointer">Répondre</a> </div>
      </div>
      <p>Bonjour,
        dans quelle mesure est-il possible de faire un traitement étanchéité sur des murs semi-enterrés ?
      </p>
      <ul class="list-inline my-0 pull-right">
        <li class="list-inline-item rating">
          Note :
          <i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i><i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i><i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i><i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i><i class="fa fa-star" style="color:#4765a0;font-size: 14px"></i>
        </li>
      </ul>
    </div>
  </div>
  <div class="responsediv row" style="display:none">
    <div class="col-md-2 text-left"></div>
    <div class="respondform col-md-9">
      <div class="u-heading-v3-1 g-mb-5">
        <h3 class="h3 u-heading-v3__title g-brd-primary  no-padding-b">
          Publier une réponse au commentaire de Smith
        </h3>
      </div>
      <form action="plugins/skyforms/blog-comment-response-process.php" method="post" class="blogcommentresponse-form sky-form comment-style" novalidate="novalidate"> <input type="hidden" name="id_article" value="103"> <input type="hidden" name="face_id" value="4"> <input type="hidden" name="id_comment" value="117">
        <fieldset>
          <div class="row">
            <div class="bon_blog_commentresponse_box form-group col-lg-6 g-mb-10"> <input type="hidden" name="blogcommentresponse"> <label class="g-mb-10" for="bon_blog_commentresponse_name">Votre nom :</label> <input class="form-control g-bg-gray-light-v5 g-bg-gray-light-v5--focus g-brd-gray-light-v5 g-rounded-1 g-pa-10" placeholder="Nom ou Pseudo" type="text" name="nom_blog_commentresponse" required=""> </div>
            <div class="bon_blog_commentresponse_box form-group col-lg-6 g-mb-10"> <label class="g-mb-10" for="bon_blog_commentresponse_email">Votre e-mail :</label> <input class="form-control g-bg-gray-light-v5 g-bg-gray-light-v5--focus g-brd-gray-light-v5 g-rounded-1 g-pa-10" placeholder="Adresse e-mail" type="email" name="email_blog_commentresponse" required=""> </div>
          </div>
          <div class="form-group g-mb-20"> <label class="g-mb-5" for="commentaire_blog_commentresponse">Votre commentaire :</label> <textarea class="countit form-control rounded-0 form-control-md w-100 faq-form g-bg-gray-light-v5 g-bg-gray-light-v5--focus g-brd-gray-light-v5 g-rounded-1 g-pa-10" name="commentaire_blog_commentresponse" rows="5" placeholder="Tapez votre commentaire ici" minlength="30" maxlength="500" required=""></textarea>
            Caractères restant : <span class="counter_desc">500 caractères</span> </div>
          <p><button type="submit" class="btn w-100 u-btn-primary text-center"><i class="fa fa-send"></i> Envoyer votre commentaire</button></p>
        </fieldset>
      </form>
      <div class="row">
        <div class="bon-blogcommentresponse-success g-mb-20"></div>
        <div class="message-blogcommentresponse message alert alert-dismissible fade show g-bg-teal g-color-white rounded-0 w-100" role="alert"> <button type="button" class="close u-alert-close--light" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
          <div class="media"> <span class="d-flex g-mr-10 g-mt-5"> <i class="icon-check g-font-size-25"></i> </span> <span class="media-body align-self-center"> <strong>Terminé !</strong> Votre réponse a bien été envoyée. Elle est en attente de modération.
            </span> </div>
        </div>
        <div class="error-blogcommentresponse message error alert alert-dismissible fade show g-bg-yellow rounded-0 w-100" role="alert"> <button type="button" class="close u-alert-close--light" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
          <div class="media"> <span class="d-flex g-mr-10 g-mt-5"> <i class="icon-info g-font-size-25"></i> </span> <span class="media-body align-self-center"> <strong>Attention !</strong> A cause d'une erreur technique, le commentaire n'a pas pu être envoyé. Veuillez recommencer plus tard.
            </span> </div>
        </div>
      </div>
    </div>
    <div class="col-md-1 text-left"><br> <span style="cursor:pointer ;color:#000000 !important" class="annulereponse">X</span> </div>
  </div>
  <div class="media  g-brd-gray-light-v4 g-ml-40 g-mb-30"> <img loading="lazy" class="d-flex g-width-60 g-height-60 rounded-circle g-mt-3 g-mr-15" src="assets/img/team/face-99.png" alt="">
    <div class="media-body u-shadow-v22 g-bg-secondary g-rounded-5 g-pa-10">
      <div class="d-flex align-items-start g-mb-15 g-mb-10--sm">
        <div class="d-block">
          <h5 class="h6 g-color-black g-font-weight-600">Stan Piotrowski</h5> <span class="d-block g-color-gray-dark-v5 g-font-size-11">14 janvier 2022 à 17:00</span>
        </div>
      </div>
      <p>Bonjour, il existe toutes sortes de procédés pour le traitement des parties enterrées : cuvelage, drainage, revêtement bitumineux. Tout dépend de la configuration de votre maison ainsi que du type d'infiltrations que vous avez.
        Bien cordialement, l'équipe SP-BATIMENT</p>
    </div>
  </div>
</div>

任何建议都将不胜感激。

【问题讨论】:

  • .removeAttribute() 是一个普通的 JS 方法...使用 jQuery,只需使用 .attr() 其中.attr(x) 是一个getter,.attr(x,y) 是一个setter。所以你应该试试.attr("id", null)。在documentation 中了解更多信息。投票结束该问题是一个错字。
  • 现在...使用id 作为动态选择器远非最佳实践。我会改用data-* 属性/属性。看看jQuery .data()
  • @LouysPatriceBessette removeAttr() is a jQuery methodshould work fine,虽然我同意让 ID 动态化确实不是一个好方法。
  • @Don'tPanic: 大声笑是的,.removeAttribute() 是普通的 JS……它会让人感到困惑……哈哈,很好 ;)
  • 完成...........

标签: javascript html jquery


【解决方案1】:

我认为您可能有点混淆了您的问题 - 您的代码删除 ids 很好,但它没有添加它们。 Here's a JSFiddle of your code - 我在每个表单中添加了一个id,这样你就可以看到会发生什么。单击链接可以删除 ids 罚款,但添加 id 不起作用。

添加不起作用仅仅是因为您走错了方向。您在匹配的.responsediv 上使用.closest(),但它通过DOM 搜索其祖先up。您要搜索的.blogcommentresponse-form.responsediv 的子代,因此您需要向下 搜索其后代。你可以通过.find() 做到这一点。

工作sn-p:

$(".response").click(function () {
    $('.blogcommentresponse-form').removeAttr('id')
    $(".responsediv").fadeOut();
    $(this).parents("div").next(".responsediv").css("visibility", "").fadeIn(100);

    // Changed .closest() to .find() here
    $(this).parents("div").next(".responsediv")
        .find(".blogcommentresponse-form")
        .attr('id','blogcommentresponse-form');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="comments">
    
  <div class="media">
    <div class="media-body">
      <div>
        <div class="ml-auto">
            <!-- LINK 1 ################################################### -->
            <a class="response">Répondre</a>
        </div>
      </div>
      <p>Bonjour, que préconisez-vous pour le renforcement de vieux murs en bauges ? Par avance merci </p>
    </div>
  </div>

  <div class="responsediv" style="display:none">
    <div class="respondform">
      <!-- FORM 1 ################################################### -->
      <!-- Give form an ID so we can check if it is removed/updated -->
      <form class="blogcommentresponse-form" id="form-1">Form 1</form>
    </div>
  </div>

  <div class="media"></div>

  <div class="media">
    <div class="media-body">
      <div>
        <div class="ml-auto">
            <!-- LINK 2 ################################################### -->
            <a class="response">Répondre 2</a>
        </div>
      </div>
      <p>Bonjour, dans quelle mesure est-il possible de faire un traitement étanchéité sur des murs semi-enterrés ?</p>
    </div>
  </div>

  <div class="responsediv" style="display:none">
    <div class="respondform">
      <!-- FORM 2 ################################################### -->
      <!-- Give form an ID so we can check if it is removed/updated -->
      <form class="blogcommentresponse-form" id="form-2">Form 2</form>
    </div>
  </div>

  <div class="media"></div>

</div>

旁注 1:发布问题时请尝试发送minimal, complete, and verifiable example。我花在这个问题上的 90% 时间只是试图深入了解 HTML 的基本结构。您添加的代码中混杂着 CSS 类和不相关的 HTML,它掩盖了我们和您的内容! - 真的需要看到并专注于对问题的感觉。我添加的 sn-p 是我将其归结为的内容;从这样的事情开始,问题几乎立即显而易见。

旁注 2:正如 cmets 中已经指出的那样,动态 ID 在语义上似乎是错误的方法。 ID 应该是唯一的、特定的元素,而不是改变的东西。我建议也许使用一个类,例如.active,来识别“活动”表单。

旁注 3:我不确定您对 HTML 有多少控制权,也许它是由插件自动生成的,但这要困难得多,而且 IMO 更易碎且容易损坏,因为语义相关的元素组没有在父元素下分组在一起。如果每个链接和表单都嵌套在一个父元素中,这将更容易,并且如果元素在将来的某些更新中更改或移动,则不太可能中断。例如:

<div class="comment">
    <div class="media">
        <a class="response"></a>
    </div>

    <div class="responsediv">
       <form class="blogcommentresponse-form"></form>
    </div>
</div>

现在查找表单的代码很简单:

$('.response').on('click', function() {
    // Find the form
    $(this).closest('.comment').find('.blogcommentresponse-form')...

【讨论】:

  • 我没有看到被滥用的closest。很棒的收获...而且我喜欢旁注 +1
  • 尊敬的先生,感谢您的投资和对我的问题的清晰解释。我不是网络开发的专业人士,我在现实生活中从事砌体工作,所以我只是试图利用我所拥有的贫乏知识为我的公司建立一个网站。下次如果我发布一些内容,我将遵循您解释的规则。我擅长 php / mysql,但在 jquery 中找到好的选择器有时对我来说很难。我必须提高我的知识,并且会阅读更多的文档。祝您 2022 年新年快乐,身体健康。
  • @StanislasPiotrowski 不客气,谢谢 :-) 祝你好运!
【解决方案2】:

我已将您的点击功能编辑为可以找到表单并添加您想要的 ID 的版本。我评论的行无法找到表单,因此我在您的代码的下一行添加了新行。这正是你想做的事情。

$(".response").click(function () { 
  $('.blogcommentresponse-form').removeAttr('id')
  $(".responsediv").fadeOut();
  $(this).parents("div").next(".responsediv").css("visibility", "").fadeIn(100);
  // $(this).parents("div").next(".responsediv").closest(".blogcommentresponse-form").attr('id','blogcommentresponse-formid'); //this code can't find the form 
  $(this).closest('.media').next(".responsediv").find(".blogcommentresponse-form").attr('id','blogcommentresponse-formid');// Right way to add id atribute
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    相关资源
    最近更新 更多