Javascript 检测 href 更改
我试图让我的 JavaScript 检查是否加载了背景(由 jquery.ready 函数加载,如果加载了背景或背景 div,那么我希望它设置 2 个 href 链接,如果背景无法加载或其他什么)出错了,然后 href 设置为空或 #。我做了一些不同的方法,并尝试混合和匹配一些代码,但似乎我无法让它正常工作,任何帮助都会很棒,我的搜索很高。谷歌的搜索量很低,在这里,我已经尝试了一段时间,让代码再次以某种方式工作,
谢谢!
I am trying to have my JavaScript check to see if a background is loaded (loaded by jquery.ready function, if the background or the background div is loaded then i want it to set 2 href links, if the background fails to load or something goes wrong then the hrefs are set to nothing or #. I have done a few different ways and tried to mix and match some code but it seems i can't get it to work right. Any help would be great, i have search high and low on google, here and have tried for a while to make the code work in one way or another.
again thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜当你说背景时,你指的是背景图像。我不相信有任何与背景图像加载相关的 JavaScript 事件可以实现您提到的效果。 jQuery onReady 和 load 函数允许您绑定到文档本身,并且仅在整个页面及其所有外部资源加载后才会触发。但是,这可能会有所帮助:
静态图像的图像加载
I'm guess that when say you background, what you're refering to is a background image. I don't believe there are any Javascript events related to background image loading that will accomplish the effect you mentioned. The jQuery onReady and load functions allow you to bind to the document itself, and will only fire once the entire page and all its external resources have loaded. However, this might help:
Image onload for static images
我认为更直接的途径可能是在 jQuery 脚本中的
标记中加载图像并处理 onerror 事件。这样您仍然可以按照当前的方式设置背景,但这将允许您以编程方式确定图像路径是否有效。
处理图像的 onerror 事件的示例 jQuery/Javascript 来替换损坏的图像
编辑:这是如何使用图像来检测错误的示例 http://jsfiddle .net/DHEqe/35/
I think a more direct route may be to load your image in an
<img />
tag in your jQuery script and handle the onerror event. This way you can still set the background the way you are currently but this will allow you to determine programmatically if the image path is valid.example on handling the onerror event for an image jQuery/Javascript to replace broken images
edit: here's an example of how to use images to detect errors http://jsfiddle.net/DHEqe/35/