您好,欢迎访问一九零五行业门户网

JS用 或 || 来兼容FireFox!_javascript技巧

js用 或 || 来兼容firefox!_javascript技巧
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>untitled document</title> </head> <body> <li> <a href="http://www.blueidea.com/articleimg/bbsimg/smile.gif"/></a> <a href="图片地址">打开</a> </li> <li> <a href="http://www.blueidea.com/articleimg/bbsimg/biggrin.gif"/></a> <a href="图片地址">打开</a> </li> <li> <a href="http://www.blueidea.com/articleimg/bbsimg/confused.gif"/></a> <a href="图片地址">打开</a> </li> </body> </html> <script language="javascript" type="text/javascript"> document.body.onclick = function(evt){ evt = evt || window.event; var o = evt.target || evt.srcelement; window.open(o.previoussibling.href || o.previoussibling.previoussibling.href); return false; } </script>
找到 document.body.onclick = function(evt),
在ie下,这个evt是不会有的,但是在firefox下(opera下好像也是)会默认传这个参数.在ie下,这个参数是 null ,想兼容,就这样写.
继续向下,
evt = evt || window.event;
在ie下,evt 就会指向:window.event,在firefox下,就会指向那个默认参数.
因为在ie下 evt || window.event 相当于: null || window.event,结果还是window.event
而在firefox下,就相当于 evt || null ,结果就是evt
相下看:
o.previoussibling.href || o.previoussibling.previoussibling.href
前面一个表达式用于ie下,后面一个用于firefox下.
因为在ie下,xmldom没有preservewhitespace这个属性,即:把空白也当作一个节点,而ie则默认为false,即把空白不看成一个节点.
这里说到了xmldom,似乎和上面所说的不相关,但是在firefox下 previoussibling就是空白,除非两个html标签之间没有任何形式的空格.
<a href="http://www.blueidea.com/articleimg/bbsimg/smile.gif"/></a>
<a href="图片地址">打开</a>
两个<a>之间有换行(属于空格的一种),所以在firefox下,取下面一个<a>的前一个节点的话,就必须用:
o.previoussibling.previoussibling.href
可能你还是没有看明白,没关系,在举个简单的:
<script> function test(p1,p2,p3){ p1 = p1 || 100; p2 = p2 || "xlingfairy"; return "p1 = " + p1 + " p2 = " + p2 + " p3 = " + p3; } alert(test()); alert(test(null,null,"blueidea.com")) </script>
以上就是js用 或 || 来兼容firefox!_javascript技巧的内容。
其它类似信息

推荐信息