如何从JSON文件添加get图像,添加类并在div中追加?

时间:2016-09-26 13:39:41

标签: javascript jquery html css json

我正在尝试在图像上添加一个类,我从本地JSON文件中获取。 我的JSON文件:

[{
    "posterPath" : "<img src = imgsMovie/MovieName/poster.jpg>"

}]

这是我从JSON获取的文件,它是一个图像标记。 现在, 我想在这个图像中有一个动态添加jQuery的类。

我的div是

<div class='rightposter'></div>

这就是我从JSON获取图像的方式

$(".rightposter").append(data[i].posterPath)//this will display my image on my page without class. 

如何在img标签内添加类?

4 个答案:

答案 0 :(得分:4)

这是一种使用jQuery插入动态构造的HTML标记的更简洁方法。

使用以下语法构建HTML并将其附加到DOM:

$div = $('.rightposter');

$('<img />', {
 'src': data[i].posterPath,
 'class': "myClass" //put your class name here
}).appendTo($div);

将您的JSON数据结构更改为以下内容:

[{
    "posterPath" : "imgsMovie/MovieName/poster.jpg"

}]

答案 1 :(得分:2)

$(".rightposter").append(data[i].poasterPath)

更改为

$(".rightposter").append($(data[i].poasterPath).addClass("your class"));

&#13;
&#13;
    $(".rightposter").append($("<img src=http://lorempixel.com/output/sports-q-c-130-67-5.jpg>").addClass("red"));
&#13;
.red { border:3px solid red }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='rightposter'></div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果这是代码中唯一的img标记,那么您可以编写$(&#39; img&#39;)。addClass(&#39;您的班级&#39;)或$(&#39; .rightposter img& #39;)。addClass(&#39;你的班级&#39;);

答案 3 :(得分:0)

您可以使用jQuery的.find()方法获取图片并在其上添加课程。

$(".rightposter").append(data[i].posterPath).find("img").addClass("myClass");