javascript委托的实-现 以带参数的函数作为参数的解决方法
我们知道,ajax 的实现原理其实就是javascript执行远程访问之后再执行原来客户端的回调函数比如:
代码
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
function ajaxTest()
{
// 指定要打开的页面
xmlhttp.open("GET", "its_a_page.aspx", true);// HTTP 请求的方式, URL, 是否异步
// 指定页面打开完之后要进行的操作.
xmlhttp.onreadystatechange = pageChange;
// 开始发起浏览请求, Mozilla 必须加 null
xmlhttp.send(null);
}
// 这个函数就是每次状态改变要调用的函数
function pageChange()
{
// 请求已完成
if (xmlhttp.readyState == 4)
{
//alert(xmlhttp.readyState);
alert(xmlhttp.responseText);
// 更新对应的 HTML 元素里面显示的内容
// 根据 ID 引用页面里面的元素 document.getElementById(元素名)
document.getElementById('weather').innerHTML = xmlhttp.responseText;
}
}
在有些情况下,我们需要给委托的函数加参数,这个时候直接指定函数就不够用了(没地方写参数?),其实我没有找到什么好办法,不过我有一个变通的办法,以下进行描述:
代码
//function with parameter to be called
function show(p)
{
var str = '<div>My test</div>'
//define the functions which have parameters
function f1() {
alert(p + ':使用了参数的第1种方法');
}
function f2() {
alert(p + ':使用了参数的第2种方法');
}
//call back the function
showWindow('我的提示框', '', 850, 250, true, ['参数方法1', f1, '参数方法2', f2]);
}
f1 f2 是show方法内的方法,用show方法的参数作为其自身的参数来模拟,然后showWindow使用f1 f2的函数名(委托)作为参数在合适的时候调用f1 f2 来执行

浙公网安备 33010602011771号