Home >Web Front-end >JS Tutorial >Summary of browser-compatible JS writing methods_javascript skills
1. Element search problem
1. document.all[name]
(1)Existing problem: Firefox does not support document.all[name]
(2) Solution: Use getElementsByName(name), getElementById(id), etc. instead.
2. Collection object problem
(1) Existing problem: You can use () to access many collection objects in IE, but you can only use [] in Firefox.
For example: document.forms("formName") can be used in IE to return the Form named "formName", but it does not work in Firefox.
(2) Solution: Use [], in the above example it can be changed to document.forms["formName"]
3. The ID of the HTML element is visible in JavaScript
(1) Existing problem: The ID in the HTML element in IE can be used directly as the subordinate object variable name of the document. Not possible in Firefox.
(2) Solution: Use getElementById("idName") instead of idName as an object variable.
4. eval(idName) gets the object
(1) Existing problem: In IE, you can use eval(idName) to obtain the HTML object with the ID idName, but not in Firefox.
(2) Solution: Use getElementById(idName) instead of eval(idName).
5. The variable name is the same as an HTML object ID
(1) Existing problem: In Firefox, because the object ID is not used as the name of the HTML object, you can use the same variable name as the HTML object ID, but not in IE.
(2) Solution: When declaring variables, always add var to avoid ambiguity, so that it can also run normally in IE. In addition, it is best not to take the same variable name as the HTML object id to reduce errors.
Note: 3, 4 and 5 all belong to the same category of questions.
6. Frame
(1) Existing problem: In IE, you can use window.top.frameId and window.top.frameName to get the Window represented by the Frame. In Firefox, you can only use window.top.frameName.
(2) Solution: Set the Id and Name of the Frame to be the same, and use window.top.frameName to access the Frame.
2. DOM operation
1. Set the text content of the element.
(1) Existing problem: IE uses innerText, while Firefox uses textContent to set the text content of elements.
(2) Solution: If the text content does not contain special characters such as "d21bf6265d53cdd4dcff18f6785f8fb4", you can use innerHTML. Otherwise, you can use:
var child = elem.firstChild; if (child != null) elem.removeChild(child); elem.appendChild(document.createTextNode(content));
2. parentElement, parent.children
(1) Existing problem: IE can use parentElement to get the parent node, and parent.children to get all the child nodes of the node. Not supported by Firefox.
(2) Solution: Use parentNode and parent.childNodes.
3. Explanation of childNodes.
(1) Existing problem: The interpretation of childNodes is different in IE and Firefox. IE will not include blank text nodes, but Firefox will.
(2) Solution: Use childNodes to filter text nodes, as follows:
var children = elem.childNodes; for (i = 0; i < children.length; i++) { if (children[i].nodeType != 3) { // 过滤文本结点 // ... } }
4. Explanation of document.getElementsByName.
(1) Existing problem: getElementsByName in IE will only check the d5fd7aea971a85678ba271703566ebfd and a1f02c36ba31691bcfe87b2722de723b elements, but under Firefox it will check all elements.
(2) Solution: Do not use getElementsByName to check elements other than d5fd7aea971a85678ba271703566ebfd and a1f02c36ba31691bcfe87b2722de723b. If you want to obtain a single element, try to use getElementById.
5. Explanation of document.getElementById.
(1) Existing problem: getElementById in IE not only checks the Id attribute, but also checks the Name attribute. When the Name attribute matches the parameter, the element will also be returned. In Firefox only the Id attribute is checked.
(2) Solution: Try to keep the Id and Name the same. Do not make the name attribute of one element the same as the id attribute of another element.
3. Events
1. Event.x and event.y issues
(1) Existing problem: In IE, the event object has x, y attributes, but not in Firefox.
(2) Solution: In Firefox, the equivalent of event.x is event.pageX. Can be used:
mX = event.x ? event.x : event.pageX;
2. window.event
(1) Existing problem: Using window.event cannot run on Firefox
(2)Solution:
Original code (can be run in IE):
<input type="button" name="someButton" value="提交" onclick="javascript:gotoSubmit()"/> ... <script language="javascript"> function gotoSubmit() { ... alert(window.event); // use window.event ... } </script>
<input type="button" name="someButton" value="提交" onclick="javascript:gotoSubmit(event)"/> ... <script language="javascript"> function gotoSubmit(evt) { evt = evt ? evt : (window.event ? window.event : null); ... alert(evt); // use evt ... } </script>
3. attachEvent和addEventListener
(1)现有问题:IE中使用attachEvent来添加事件,Firefox中使用addEventListener。
(2)解决方法:如下,注意事件参数的区别,一个是click,一个是onclick。
if (document.attachEvent) document.attachEvent("click", clickHandler,false);
else document.addEventListener("onclick",clickHandler);
四、语法
1. const
(1)现有问题:在IE中不能使用const关键字。如const constVar = 32;在IE中这是语法错误。
(2)解决方法:不使用const,以var代替。
2. 多余的逗号
(1)现有问题:firefox中对象文字常量容许多余的逗号,在IE中不允许。下面语句在IE中非法。
var obj = { 'key' : 'aaa', }
(2)解决方法:去掉多余逗号。
五、XML
1. 创建XMLHttpRequest
(1)现有问题:Firefox使用XMLHttpRequest,IE使用ActiveXObject。
(2)解决方法:
if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); }
2. 创建DOM
(1)现有问题:Firefox和IE创建DOM的方式不同。
(2)解决方法:
function createXmlDom() { var oXmlDom; if (Window.ActiveXObject) { // IE oXmlDom = new ActiveXObject("Microsoft.XmlDom"); } else { // Firefox oXmlDom = document.implementation.createDocument("", "", null); } }
3. 加载XML
(1)现有问题:如果要加载外部文件IE和Firefox都可以用:
oXmlDom.async=false; // 这在Firefox中是必须的
oXmlDom.load("test.xml");
但是它们加载xml字符串的方式不一样,IE中直接可以使用oXmlDom.loadXML("4216313e5055da45c6d0ded129c5d6443e8e92382b62183bf2604fde8a42078bc02ae4fdd442eb2210bebb17feeb95b4"),而Firefox要使用DOMParser:
var oParser = new DOMParser();
var oXmlDom = oParser.parseFromString("66efc7746bfc38acf99d97c3d23ab9c7", "text/xml");
(2)解决方法:比较好的方法是给Firefox产生的XMLDom加上loadXML方法:
if (isFirefox) { // 需要浏览器检测
Document.prototype.loadXML = function(sXml) { var oParser = new DOMParser(); var oXmlDom = oParser.parseFromString(sXml, "text/xml"); while (this.firstChild) this.removeChild(this.firstChild); for (var i = 0; i < oXmlDom.childNodes.length; i++) { var oNewNode = this.importNode(oXmlDom.childNodes[i], true); this.appendChild(oNewNode); } } }
这样在IE和Firefox就可以调用loadXML方法了。
4. XPath支持
(1)现有问题:IE中可以直接用XmlDOM的selectNodes来根据XPath表示式来选择结点,Firefox则比较复杂,需要使用XPathEvaluator。
IE:
var lstNodes = oXmlDom.documentElement.selectNodes("employee/name"); for (var i = 0; i < lstNodes.length; i++) { alert(lstNodes[i].firstChild.nodeValue); }
Firefox:
var oEvaluator = new XPathEvaluator(); var oResult = oEvaluator.evaluate("employee/name", oXmlDom.documentElement, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); var oElement = oResult.iterateNext(); while (oElement) { alert(oElement.firstChild.nodeValue); oElement = oResult.iterateNext(); }
(2)解决方法:比较好的方法给Firefox的Element添加selectNodes方法。
if (isFirefox) { // 需要浏览器检测 Element.prototype.selectNodes = function(sXPath) { var oEvaluator = new XPathEvaluator(); var oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); var aNodes = new Array(); if (oResult != null) { var oElement = oResult.iterateNext(); while (oElement) { aNodes.push(oElement); oElement = oResult.iterateNext(); } } return aNodes; } }
这样在IE和Firefox中就都可以调用selectNodes方法了。
5. XSLT支持
(1)现有问题:IE中可以使用XmlDOM的transferNode方法将其转换成html,而Firefox需要使用XSLTProcessor。
IE:
oXmlDom.load("employee.xml"); oXslDom.load("employee.xslt"); var sResult=oXmlDom.transformNode(oXslDom);
Firefox:
var oProcessor = new XSLTProcessor(); oProcessor.importStylesheet(oXslDom); var oResultDom = oProcessor.transformToDocument(oXmlDom); var oSerializer = new XMLSerializer(); var sXml = oSerializer.serializeToString(oResultDom, "text/xml"); alert(sXml);
(2)解决方法:比较好的方法给Firefox的Node添加transferNode方法。
if (isFirefox) { // 需要浏览器检测 Node.prototype.transformNode = function(oXslDom) { var oProcessor = new XSLTProcessor(); oProcessor.importStylesheet(oXslDom); var oResultDom = oProcessor.transformToDocument(oXmlDom); var oSerializer = new XMLSerializer(); var sXml = oSerializer.serializeToString(oResultDom, "text/xml"); return sXml; } }
这样在IE和Firefox中就都可以调用transferNode方法了。
以上就是针对浏览器兼容的JS写法的总结,希望对大家的学习有所帮助。