在jQuery中创建图像标记无效

Creating image tag in jQuery not working?

本文关键字:无效 图像 创建 jQuery      更新时间:2023-09-26

index.html

<html>
    <head>
        <script src="//code.jquery.com/jquery-2.0.0.min.js"></script>
        <script src="jquery.js"></script>
    </head>
    <body>
        <div id="myDiv" name="myDiv" title="Example Div Element">

        </div>
    </body>
</html>

jquery.js

$.ajax
({
 type: "GET",
 url: "url",
 dataType: 'image/png',
 async: false,
 beforeSend: function (xhr) {
 xhr.withCredentials = true;
 xhr.setRequestHeader("Authorization", "Bearer xxx");
 },
 complete: function (data) {
 console.log("yello");
 $('#myDiv').html('<img id="target">');
 }
 });

问题很简单,

为什么这条线路不工作?$('#myDiv').html('<img id="target">');当我检查页面的来源时,没有显示任何内容,也没有图像标记。我不太明白为什么,因为我确信我做的每件事都是正确的。

谢谢!

将函数封装在.ready((:中

 $(function()
 {
     $.ajax
     ({
         type: "GET",
         url: "url",
         dataType: 'image/png',
         async: false,
         beforeSend: function (xhr) {
             xhr.withCredentials = true;
             xhr.setRequestHeader("Authorization", "Bearer xxx");
         },
         complete: function (data) {
             console.log("yello");
             $('#myDiv').html('<img id="target">');
         }
     });
 });

这样可以确保在加载DOM之后调用ajax方法。

如果您发布的javascript是完整的jquery.js文件,那么在浏览器呈现div标记之前,javascript正在运行,因此jquery选择器找不到任何东西,因此您的console.log调用返回undefined。

下面是我一起验证javascript的一个快速步骤,请注意,我将图像创建封装在$(function(){});块中。这是document.ready(function(({}(的jquery简写;

在您的代码之后尝试console.log($('#myDiv').html()),并在控制台中查看值,您会在那里找到图像,但它不会显示在源代码视图