Friday, March 03, 2006

Javascript on Firefox & IE

Javascript on Firefox & IE

JavaScript语言中的Literal Syntax特性
http://www.cnblogs.com/birdshome/archive/2005/02/26/105867.html

1. XmlHttp: IE是用ActiveX方式,而Firefox是内置实现的
xmlHttp=new ActiveXObject('Msxml2.XMLHTTP'); //IE
xmlHttp=new XMLHttpRequest(); //FF
可以用下面的写法,可以比较好的兼容IE和Firefox:
function createXH(){
var A=null;
try { A=new ActiveXObject('Msxml2.XMLHTTP') } catch(e) {
try{A=new ActiveXObject('Microsoft.XMLHTTP') } catch(oc) { A=null }
}
if ( !A && typeof XMLHttpRequest != 'undefined' ) { A=new XMLHttpRequest() }
return A
}

请求和接收回应
var xmlhttp=createXH();
xmlhttp.open('POST', 'Message/CheckNew.aspx', false); //false - 同步执行的方式 ; true - 异步执行的方式
xmlhttp.send(''); // 这里也可以在请求时发送一些数据,如果没有数据,也要发个空数据
var rt=xmlhttp.responseText;

异步执行下接收回应:
var xmlhttp = createXH();
function checkNewMessages(){
xmlhttp.open('POST', 'Message/CheckNew.aspx', true);
xmlhttp.onreadystatechange=continue;
xmlhttp.send('');
}
function continue(){
if(xmlhttp.readyState==4){
var rt = xmlhttp.responseText;
}
}

2. event object
In Firefox, it's passed in to the event handler
Unfortunately, IE holds the event in a window attribute instead of passing it in
function shutdown(ev) {
ev = window.ev ev;
....
}

3. What attributes of the Event should be inspected
Element - target (Firefox), srcElement (IE)
Event type - type
Key code - which (Firefox), keyCode (IE)
Key modifiers - altKey, ctrlKey, shiftKey
Mouse buttons - button: In IE, 1 is left, 2 is right, and middle is 4. Value represents the sum of all buttons being pressed
In Firefox, 0 is left, 1 is middle, and 2 is right.
Mouse position - clientX, clientY

4. How should event handlers be dynamically registered
quitButton.onclick = shutdown (IE)
quitButton.attachEvent('onclick', shutdown) (IE)
quitButton.addEventListener('click', shutdown, false) (Firefox)

No comments: