验证文件的 href 链接
我正在使用 JQuery 动态添加图像文件的链接。
+ "<td><a class='IconButton' id='trkimg" + k + "' href='IMSTORE\/" + trackings[k].Image + "'><span class='ui-icon ui-icon-image'></span></td>"
此代码检查是否从数据库返回了值,如果未返回任何内容,则隐藏链接:
if (trackings[k].Image == null) { $("#trkimg" + k).html(""); $("#trkimg" + k).removeClass('CustomButton'); }
How can I use JQuery to validate the returned file确实存在,如果不存在,则显示不同的图像?
I am using JQuery to dynamically add a link for an image file.
+ "<td><a class='IconButton' id='trkimg" + k + "' href='IMSTORE\/" + trackings[k].Image + "'><span class='ui-icon ui-icon-image'></span></td>"
This code checks that a value was returned from the database and hides the link if nothing was returned:
if (trackings[k].Image == null) { $("#trkimg" + k).html(""); $("#trkimg" + k).removeClass('CustomButton'); }
How can I use JQuery to validate that the file returned actually exists, and if it doesn't exist, display a different image?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JavaScript 无法查看您服务器上的文件。我猜你可以向服务器端发出 ajax 请求来检查文件是否存在。
Javascript cannot see the files on your server. You could do an ajax request to something server side to check if the file exists I guess.
按照 SeanJA 的建议,您可以使用 ajax 来“测试”图像,然后在
success
回调中实际附加图像,或者在error
中尝试另一个打回来。您请求该图像两次,但也许在第一次尝试后它就被缓存了。没有把握。
如果您想实际使用返回的图像,则需要对其进行编码。这是有关如何执行此操作的说明的链接。不过还没有尝试过。
http://emilsblog.lerch.org/ 2009/07/javascript-hacks-using-xhr-to-load.html
不确定这是否是最好的方法,但似乎可行。
Along the lines of what SeanJA suggested, you could use ajax to 'test' for the image, then actually append the image in the
success
callback, or try another in theerror
callback.You're requesting the image twice, but maybe it is cached after the first try. Not sure.
If you want to actually use the image returned, it needs to be encoded. Here's a link to instructions on how to do it. Haven't tried it, though.
http://emilsblog.lerch.org/2009/07/javascript-hacks-using-xhr-to-load.html
Not sure if this is the best way, but seems to work.