为什么有的时候点击事件触发第二次才执行?

function comeBack(comeBack,flag){

    if(this.flag){    

        $(comeBack).css('display','block');

        this.flag = false;

    }else{

        $(comeBack).css('display','none');

        this.flag = true;

    };

};

$('#comeBack').on('click',function(){

    var flag1 = true;

    comeBack('#comeBack .img2',flag1);

});


哆啦的时光机
浏览 745回答 1
1回答

慕容森

function comeBack(comeBack,flag){&nbsp; &nbsp; //这里用this.flag是给你的window加了flag属性&nbsp; &nbsp; //第一次没有初始化,是undefined,走else,else里设为true,第二次走if&nbsp; &nbsp; if(this.flag){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $(comeBack).css('display','block');&nbsp; &nbsp; &nbsp; &nbsp; this.flag = false;&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; $(comeBack).css('display','none');&nbsp; &nbsp; &nbsp; &nbsp; this.flag = true;&nbsp; &nbsp; };};$('#comeBack').on('click',function(){&nbsp; &nbsp; //这个flag1是局部变量,每次进来都会初始化一次,传进去永远是true,只执行if,不是没有效果&nbsp; &nbsp; var flag1 = true;&nbsp; &nbsp; comeBack('#comeBack .img2',flag1);});正确做法:flag放在外面,作为全局变量//实际声明的是window.flagvar flag = true;//实际声明的是window.comeBack,它的this就是windowfunction comeBack(comeBack){&nbsp; &nbsp; if(this.flag){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $(comeBack).css('display','block');&nbsp; &nbsp; &nbsp; &nbsp; this.flag = false;&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; $(comeBack).css('display','none');&nbsp; &nbsp; &nbsp; &nbsp; this.flag = true;&nbsp; &nbsp; };};$('#comeBack').on('click',function(){&nbsp; &nbsp; comeBack('#comeBack .img2');});推荐做法:使用类+css控制<div id="#comeBack">&nbsp; &nbsp; <img class="img2 hidden"></img></div>.hidden {&nbsp; &nbsp; display: none;}$('#comeBack').on('click',function(){&nbsp; &nbsp; $img = $(this).children('.img2');&nbsp; &nbsp; if($img.hasClass('hidden')){&nbsp; &nbsp; &nbsp; &nbsp; $img.removeClass('hidden');&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; $img.addClass('hidden');&nbsp; &nbsp; }});或者data api<div id="comeBack" data-status="hidden">&nbsp; &nbsp; <img class="img2"></img></div>$('#comeBack').on('click',function(){&nbsp; &nbsp; $this = $(this);&nbsp; &nbsp; status = $this.data('status');&nbsp; &nbsp; if(status === 'hidden'){&nbsp; &nbsp; &nbsp; &nbsp; $this.children('.img2').css('display', 'block');&nbsp; &nbsp; &nbsp; &nbsp; $this.data('status', 'show');&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; $this.children('.img2').css('display', 'none');&nbsp; &nbsp; &nbsp; &nbsp; $this.data('status', 'hidden');&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript