【发布时间】:2018-06-26 02:02:48
【问题描述】:
对此我感到有点羞愧,但让 Jquery 选择我的文章正文、获取子图像并向其中添加类时遇到了很多麻烦。
我试过用post-body和card-body替换card,但也没有运气。
我刚开始学jq。
我搜索了堆栈溢出,我相信我正确使用了 css 选择器。
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')正在寻找<card>。我假设一个错字。 -
另外,
.children()只寻找 立即 孩子。你需要.find()。 -
试试
$('card')到$('.card')
标签: javascript jquery html twitter-bootstrap