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/