拦截双重属性javascript函数,如document.getElementById
Intercept double properties javascript function like document.getElementById
我有一个JavaScript脚本,里面有很多这样的函数
document.getElementById(id)
并且我不希望脚本在此函数的任何未定义返回时停止,因此解决方案是使用钩子类似的函数拦截任何调用,我使用以下代码进行拦截:
var f = document.getElementById.bind(document);
document.getElementById = function (id) {
if(f(id) !== null) return true;
return false;
}
window.onload = function () {
document.getElementById('ajax').style.display = "block";
}
现在,这个脚本对于一级链接属性工作得很好,像这样:
document.getElementById("html").innerHtml = "Hello"
或
document.getElementById("txt").disabled = true;
脚本将绕过该函数,并且在返回false时不会抛出任何错误,但是当添加另一个属性时,像这样:
document.getElementById('ajax').style.display = "block";
则脚本将抛出:
TypeError: . getelementbyid(…)。样式未定义
如果我们有一些东西导致脚本死亡时发现结果为null(没有DOM元素与该id)从函数挂钩,这将解决问题,但我找不到做死亡或退出函数,而不是返回false。
您的替换函数返回true
或false
。它永远不会返回real document.getElementById()
的原始返回值。
如果您真的想让这样的事情工作,您将需要返回一个对象,该对象模拟代码可能期望从真正的DOM节点获得的许多DOM api。只返回false
不会使任何事情变得更好。
相关文章:
- 正在寻找比$(document).ready慢的$(window).load的替代方案
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 如何用更合适的内容替换document.write
- document.styleSheets不返回任何内容
- jQuery document.ready not working
- $(document).height()在刷新时随机化值(Safari 5.1.10)
- reactjs this.refs vs document.getElementById
- 如何通过adf中的document.getElementById获取inputText字段值
- window.opener.document在ie中不起作用
- contentWindow.document.body is null
- document.applet.method在Mounatin Lion上抛出safari 6+JDK7异常
- document.getElementById(“st”).click();不起作用
- $(document).height和$(window).heaght都返回相同的值-使用的是正确的doctype
- jQuery document.ready停止代码
- document.getElementById并使用id名称
- 使用jQuery 1.8.1准备好多个$(document).是否有任何开销
- document.getElementById在js中不起作用
- document.getElementById.style.backgroundImage not working
- 停止对document.ready函数的重定向/刷新
- 是否可以 document.getElementsByTagName('head')[0] ever 返回 null