Javascript 如何为setAttribute添加回调?
是否可以在Prototype上的Javascript 如何为setAttribute添加回调?,javascript,callback,prototype,Javascript,Callback,Prototype,是否可以在Prototype上的setAttribute上添加回调 对于本例,我想在setAttribute()完成时显示一个警报(“完成!”) img.setAttribute("src", "http://blabla.com/c.jpg"); 你可以,但我不推荐 (function() { var elementSetAttribute = Element.prototype.setAttribute; Element.prototype.setAttribute =
setAttribute
上添加回调
对于本例,我想在setAttribute()
完成时显示一个警报(“完成!”)
img.setAttribute("src", "http://blabla.com/c.jpg");
你可以,但我不推荐
(function() {
var elementSetAttribute = Element.prototype.setAttribute;
Element.prototype.setAttribute = function() {
whateverFunctionYouWant.call(this);
return elementSetAttribute.apply(this, arguments);
}
})();
当您执行诸如document.links[0].setAttribute('href','/')之类的操作时,这将调用whateverFunctionYouWant()
当您更改img
元素的src
属性并且新资源已加载时,您似乎希望此函数调用回调
(function() {
var HTMLImageElementSetAttribute = HTMLImageElement.prototype.setAttribute;
HTMLImageElement.prototype.setAttribute = function(attribute, value) {
var image;
if (attribute == 'src') {
image = new Image;
image.addEventListener('load', loaded, false);
image.src = value;
}
return HTMLImageElementSetAttribute.apply(this, arguments);
}
})();
您可以在这里使用第三个参数重载setAttribute()
,这将是回调
根据我的观点和经验,我会创建一个不同的函数来代替它。修改原型是一回事,但是重载本机DOM方法来做额外的事情听起来像是在招惹麻烦,特别是当不熟悉您所做工作的开发人员查看代码时
不言而喻,如果您希望后一个示例工作attachEvent()
回退添加事件侦听器。可能不是黄金解决方案,但是
img.setAttribute("src", "http://blabla.com/c.jpg");
img.onload = imageCallback;
function imageCallback() { ... }
如果您对jQuery感兴趣,有一个名为的插件可能会有所帮助 为什么?
setAttribute
不是异步的。重新更新:以您的示例为例,您是否询问在映像加载完成后如何运行函数?因为这将在属性设置完成后的某个时间发生。为了澄清,您是说Prototype作为JavaScript库还是Prototype作为JavaScript对象上的Prototype
属性?Prototype作为JavaScriptlibrary@Steffi你的意思是当你更改img
元素的src
属性并且新资源已经下载时,你想要一个回调吗?我没什么要说的了。你太棒了。我发现你的函数有一个问题:如果图像已经加载一次,回调就不会执行。当load
事件可用时,轮询不是最好的解决方案。如果img
已经加载,会发生什么?每次我设置属性时都需要进行回调。@Steffi,但是当您setAttribute
Yes时,您不是想要回调吗。setAttribute然后调用setAttribute。@Steffi,试试我上面链接的插件