javascript - 我想创建一个 js 文件并且必须动态加载 img 标签

标签 javascript html css

function loadApp(){

    var img = document.createElement("img");
    img.src = "images/bmw-918407_1280.jpg";
    src.appendChild(img);

}
window.onload = loadApp;

创建一个加载文档时运行的 loadApp 函数。在 loadApp 函数中,我希望你调用一个函数:createImage(“images/imageName.png”)。

如何做到这一点?

最佳答案

您还需要父项选择器。

// parentSelector is the parent of your image element. Pass the parameter whatever you want.
// imgSource is the URL of your image. Make sure it's appropriate image link (not broken)
function createAndPush(parentSelector, imgSource){
    var img = $('<img>');
    img.attr('src', imgSource);
    img.appendTo(parentSelector)
}

// Call in the onLoad or document ready.
createAndPush('#footer', 'https://cdn.sstatic.net/Img/unified/sprites.svg?v=e5e58ae7df45')

在jQuery onReady中调用函数如下:

$(document).ready(function(){
   createAndPush('#footer', 'https://cdn.sstatic.net/Img/unified/sprites.svg?v=e5e58ae7df45')
})

这是代码片段

// parentSelector is the parent of your image element. Pass the parameter whatever you want.
// imgSource is the URL of your image. Make sure it's appropriate image link (not broken)
function createAndPush(parentSelector, imgSource){
    var img = $('<img>');
    img.attr('src', imgSource);
    img.appendTo(parentSelector)
}


$(document).ready(function(){
   createAndPush('#footer', 'https://cdn.sstatic.net/Img/unified/sprites.svg?v=e5e58ae7df45')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="footer">

</div>

关于javascript - 我想创建一个 js 文件并且必须动态加载 img 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55472571/

相关文章:

javascript - 如何使 slider 图像变暗?

javascript - 如何将 onclick 事件添加到表列?

javascript - JQuery 无法识别类

javascript - 如何垂直对齐 float 的、流动的 div 中的内容?

javascript - 插入 react native 的 typescript

javascript - 我如何从 AngularJS 中的编译中获得 promise ?

javascript - session 超时后自动显示警报消息,无需手动刷新页面

css - 从 Bootstrap 4 网格中删除装订线

javascript - 处理 html 表单响应

javascript - 使用 Javascript 更改 CSS 参数