【问题标题】:JQuery not adding class to child images of parent divJQuery 不向父 div 的子图像添加类
【发布时间】:2018-06-26 02:02:48
【问题描述】:

对此我感到有点羞愧,但让 Jquery 选择我的文章正文、获取子图像并向其中添加类时遇到了很多麻烦。 我试过用post-bodycard-body替换card,但也没有运气。

我刚开始学jq。

我搜索了堆栈溢出,我相信我正确使用了 css 选择器。

addClass to body won't work

How to add a class to body tag?

How to add the img-responsive class in javascript

我很确定我做得正确(尽管由于某种原因它无法正常工作),但我不确定问题可能出在哪里。

基础 HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    ...
    {% load static %}

    {% block js %}
    {% endblock %}
    ...
</head>

帖子详细信息模板:

{% extends "base_generic.html" %}

{% block js %}
<script type="text/javascript" src="{% static 'js/post-detail.js' %}"></script>

{% endblock %}

  <div class="card">
            <div class="card-body post-body">

                 // image added here in admin by using 'ckeditor'
                 <img alt="" src="..." style="height:792px; width:1280px">  

            </div>
  </div>

JS:

$(document).ready(function(){
  $('card').children('img').each(function(){
    $(this).addClass('d-block img-fluid mx-auto');
  });
});

我不明白为什么它没有选择图像标签并将类添加到其中。有什么想法吗?

编辑:如果您遇到类似的问题,如果您检查浏览器的控制台日志,您可能会看到ReferenceError: "x" is not defined。确保先加载 jq。

【问题讨论】:

  • $('card') 正在寻找&lt;card&gt;。我假设一个错字。
  • 另外,.children() 只寻找 立即 孩子。你需要.find()
  • 试试$('card')$('.card')

标签: javascript jquery html twitter-bootstrap


【解决方案1】:

有几个问题。首先,您的选择器正在执行$('card'),它试图找到一个不存在的&lt;card&gt; 元素。既然是类,你要使用$('.card')

其次,图像不是卡片的直接子级。它们嵌套了两层,所以children() 不起作用。您可以使用find() 来解决此问题。

但是,您的代码可以同时修复和减少。

$('.card img').addClass('d-block img-fluid mx-auto');`

没有必要写出显式的 each。当您执行 addClass 之类的方法时,jQuery 会自动循环遍历其堆栈中的每个结果。

【讨论】:

  • 奇怪的是,在我开始猜测代码并获得创意之前,我确实尝试过。我确实发现我没有加载库:(谢谢你的帮助
【解决方案2】:

只需使用$('.card img').each(......

$(document).ready(function(){
  $('.card img').each(function(el){
    $(this).addClass('d-block img-fluid mx-auto');
    // Only for demonstration
    console.log('Class added: ' + $(this).attr('class'));
  });
});
img{
   max-height: 100px;
   max-width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
  <div class="card-body post-body">

       // image added here in admin by using 'ckeditor'
       <img alt="" src="https://www.istockphoto.com/resources/images/PhotoFTLP/img_67920257.jpg" style="height:792px; width:1280px"/>  

  </div>
</div>

【讨论】:

    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 2011-06-05
    相关资源
    最近更新 更多