在图像上使用load()方法时未显示警报

Alert not showing when using load() method on image

本文关键字:方法 显示 图像 load      更新时间:2023-09-26

$('#rafale').load(function (){   	
    alert('hello');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img id="rafale" src="https://signup.na.leagueoflegends.com/theme/signup_new_theme/img/logo-lol.png" alt="Rafale Jet" >

上述代码用于在加载图像后显示alert框,但未显示。相反,它给出了一个错误:

jquery-3.1.1.min.js:4未捕获类型错误:a.indexOf不是>函数(…(

此问题是由于对jQuery v3.x中的load()方法进行了修改。它不再创建load事件处理程序,而是尝试发出AJAX请求将内容加载到所选元素中,因此错误是由于缺少参数引起的。

要执行所需操作,请改用on('load', fn)。试试这个:

$('#rafale').on('load', function(){      
    alert('hello');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img id="rafale" src="https://i.imgur.com/F5iJY.jpg" alt="Rafale Jet" >

请注意,我已将图像源更改为一个有效位置,以便事件能够正确触发。您需要挂接到error事件来捕获404和其他响应代码。

load((方法在jQuery版本1.8中被弃用[已经过时],在版本3.0中被删除。

$('#rafale').on('load', function (){      
    alert('Test');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<img id="rafale" src="http://www.clipartkid.com/images/607/country-and-mobile-redirect-for-wordpress-dwpsxm-clipart.jpg" alt="" />
<p><b>Note:</b> Depending on the browser, the load event may not trigger if the image is cached.</p>
</body>