48. 이벤트2

hanahana·2022년 8월 22일
0
post-thumbnail

이벤트 강제 발생(trigger)


        $('#btn1').on("click",function(){
           update(0)           
        });

        $('#btn2').on("click",function(){
            update(1)
        });

        $('#btn3').on("click",function(){         
            update(2)
          });

        $('#lastBtn').on("click",function(){
            $("#btn1").trigger("click");
            $("#btn2").trigger("click");
            $("#btn3").trigger("click");

        });

        function update(val){
            var levle = parseInt($("span").eq(val).text());
            $("span").eq(val).text(levle+1)
        }

이벤트 연결

$("#btn-2").on("click",function(){
//btn2에 함수를 넣는다.

            $('#btn-1').text("Click")
//btn2를 누르면 btn1의 텍스트값이 Click으로 변한다.
            $("#btn-1").on("click",function(){
//btn-1을 누르면
//h1에Oh!!라는 문자열이 추가된다.
                $("#h1").append("Oh!!");
            })
        })
//이렇게 함수를 넣으면 btn2를 눌렀을때 btn1버튼을누르면 동작하는 함수가 생긴다

        $("#btn-3").on("click",function(){
            $('#btn-1').text("nothing..")
            $("#btn-1").off("click");
        })

        $("#btnOnOff").on("click",function(){
           

           if($('#btnOnOff').text()=="on"){
            $('#btnOnOff').text("off")
            $('#div1').off("mouseenter");
            $('#div1').off("mouseleave");
           }
           else{
            $('#btnOnOff').text("on")

           $('#div1').on("mouseenter",function(){
            $('#div1').css('background','red');
           })
           $('#div1').on("mouseleave",function(){
            $('#div1').css('background','white');
           })

           }

        })

이벤트 버블링 막기 및 기본 이벤트 제거

stopPropagation() : 이벤트 전달 제거

preventDefault() : 기본 이벤트 제거


        $("#h1-click").on("click",function(){
            alert("h1 클릭");
        })
        $("#span-click").on("click",function(e){
            alert("span 클릭");
            //e.stopPropagation(); <- 이렇게 사용해도 작동함
            return false; //함수 윗쪽에 이벤트 실행후 모든 이벤트를 리턴으로 닫음
        })

  
        $('a').on("click",function(){
            alert("클릭이벤트 발생")
            return false;
        });
 
profile
hello world

0개의 댓글