Javascript/jQuery 前置图像

Javascript/jQuery prepend images

我是一名学生,刚接触 JS 和 jQuery。我正在尝试做一个 facebook-like 小项目,因为我可以在里面放很多不同的东西。现在 HTML 只是静态的,但一旦我有了更多的知识,我打算把它变成 user-generated.

我有不同的 'Facebook' post。每个 post 是一篇文章,整体在标题为 'newsfeed' 的部分中,文章的语法如下:

然后我添加了一些 jQuery/JS 代码来添加个人资料图片

profilePics = function () {
    var name = $('article h1').attr('class');
    name = capitalizeFirstLetter(name);
    console.log(name);
    var path = '../media/profile/' + name + '_Square_0.png';
    console.log(path);
    $('article h1').prepend('<img src="' + path + '" alt="image of ' + name + '">')
};

当我运行这个的时候,显示的是图片的alt-text,说明打不开图片。我的问题分为两部分:

  1. 我triple-checked路径,所以基本上唯一可能出错的地方就是我没有去正确的parent-directory。我是从 JS 文件还是它所在的目录开始计算位置?

  2. 我想为每个添加不同的图片(不确定多少)post。现在它查看 class 的第一个 post,然后将其添加到所有 posts

要在任何 <h1> 上添加不同的图片,您必须遍历它们。并且你的http图片路径必须是绝对的,而不是相对的。

profilePics = function () {

    var imgPath = '/http-img-path/from/web-root/';

    $('article h1').each(function() {
        var name = $(this).attr('class');
        $(this).prepend("<img src='"+imgPath + name + "_Square_0.png' alt='image of "+name+"'");

    });

};