js调用同一个方法两次,只执行第二个方法。

在同一个js文件里,有两个写好的方法 a,b。当c方法调用时,可以运行,但是如果两个方法c,d同时调用上述的ab方法只执行第二个d方法。怎么办,是把a,b做成封包还是放到其他js文件。

这两个是操作方法

function a(first) { //移动目标方法
    first.onmousedown = function (e) {      //把onclick改成mouseover就是一获得焦点图片就跟随鼠标移动,onmousedown鼠标拖动效果
        e.preventDefault && e.preventDefault(); //去掉图片拖动响应  重要!!!
        var x = e.clientX - first.offsetLeft;
        var y = e.clientY - first.offsetTop;
        document.onmousemove = function (e) {
            first.style.left = e.clientX - x + "px";
            first.style.top = e.clientY - y + "px";
        };
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup=null;
        }
    }
};

//Collision detection,碰撞检测,first为第一个传入参数,为移动的元素,second为第二个传入的参数,为静止的元素。method为方法,即碰撞后调用的方法;
function  b(first,second,method) {
    //碰撞检测
    /*    var first=document.getElementById("#");//动
        var second=document.getElementById("#");//静*/
    first.onmousemove=function () {  //在first移动时检测碰撞
        var t1 = first.offsetTop,
            l1 = first.offsetLeft,
            r1 = first.offsetLeft + first.offsetWidth,
            b1 = first.offsetTop + first.offsetHeight;
        var t2 = second.offsetTop,
            l2 = second.offsetLeft,
            r2 = second.offsetLeft + second.offsetWidth,
            b2 = second.offsetTop + second.offsetHeight;
        var noConflict=b1<t2 || l1>r2 || t1>b2 || r1<l2;// 表示没碰上
        if(!noConflict){  //返回值给调用的方法进行判断;×
            // return true;
            method.f();  //调用在json数据里写好的函数方法,形成动态加载;
            // method();  //换一种思路,里面的操作调用其他方法,形成嵌套;
        }
    }
}

两个调用

function c() {
    var method={   //测试采用json方法传递定义好的函数
        name:"method",
        f:function () { //方法定义区间,请写入first与second碰撞发生的效果;
          //语句
    }
    move(first);
    CD(first,second,method);
}

function d(){
    var method={
        name:"method",
        f:function () {
               //语句
    }
        }
       move(first);
       CD(first,second,method);

}
cd之间的first,second,method都是不一样的。
阅读 6.3k
2 个回答

通过赋值的方式对同一个对象绑定事件,后绑定的事件会替换掉前一个。如果你需要两个都保留,可以使用 addEventListener

根据边城大神的回答,进行调整,增加了if判断来为事件执行的顺序排序。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题