Alireza
Alireza

Reputation: 6868

jQuery bind event does not work at all

I did everything I could to make it happen, but without success.

The problem is that I create an element on runtime then bind a function to the element like the following code:

$(document).ready(function() {

  $('.rem').click(function() {
    $("body").append('<a id="runtime" href="javascript:void(0);">runtime</a>');
  });

  $('#runtime').bind('click', func_name());

});

//End of doc
function func_name() {
  alert('I got it!');
}

In the HTML code I have a label like below:

<div id="body">
  <label class="rem">click me</label>
</div>

My second attempt

$(document).ready(function() {

  $('.rem').click(function() {
    $("body").append('<a id="runtime" href="javascript:void(0);">runtime</a>');
  });

  $('#runtime').bind('click',function() {
    alert($(this).text());
  });

});
//End of doc

HTML code:

<div id="body">
  <label class="rem">click me</label>
</div>

Upvotes: 3

Views: 20102

Answers (4)

이상준
이상준

Reputation: 1

//-------------------------------------------------------
//  event bind
//  ex) $U.eventbind(window,"onresize",chart_common.draw);
//-------------------------------------------------------
,   eventbind   :
        function (vobj, vEvent, pFunction, vrecheck) {
            
            let obj = vobj;
            if (typeof(vobj) === "string"){
                obj =   $hD(vobj);  
            }
            
            let vFunction   =   pFunction.bind();   
            let vkey            =   pFunction.toString().replaceAll(/ /g,"");
            $GC._U_EVENT_CAPTION.push(vkey)
            $GC._U_EVENT_OBJ.push(vFunction);
                
            if ($U.isNull(obj)){
                if (vrecheck === true){
                } else{
                    setTimeout(function(){  //--**  화면로드등으로 인해 시간이 지체되는 경우 3초뒤 한번더 체크
                        $U.eventbind(vobj, vEvent, vFunction, true);
                    },3000);                    
                } 
                return;
            } 
            
            if (obj === window){
                    obj.addEventListener(vEvent.substring(2), vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
                    return;
            }
            
            if ($U.isNullOrEmpty(vFunction)) return;
            if ($U.isNull(obj.length) || obj.length === 0){
                if (obj.addEventListener){
                    obj.addEventListener(vEvent.substring(2), vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
                } else {
                    if (obj[vEvent]){
                        obj.attachEvent(vEvent, vFunction);
                    } else {
                        obj[vEvent] =   vFunction;
                    }
                }
            } else {
                for (var q=0,eoobj;eoobj=obj[q];q+=1){
                    if (eoobj.addEventListener){
                        eoobj.addEventListener(vEvent.substring(2), vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
                    } else {
                        if (eoobj[vEvent]){
                            eoobj.attachEvent(vEvent, vFunction);
                        } else {
                            eoobj[vEvent]   =   vFunction;
                        }
                    }
                }
            }
        }

//-------------------------------------------------------
//  event unbind
//      addEvent 시 리턴받은 토큰이나 function Name 로 사용시
//-------------------------------------------------------
,   eventunbind :
        function (vobj, vEvent, pFunction, vrecheck) {

            let obj = vobj;
            if (typeof(vobj) === "string"){
                obj =   $hD(vobj);  
            }
            
            let vFunction   =   pFunction;
            let vkey            =   pFunction.toString().replaceAll(/ /g,"");
            for(let iuyt=0,chkey; chkey=$GC._U_EVENT_CAPTION[iuyt]; iuyt+=1 ){
                if (chkey === vkey){
                    vFunction   =   $GC._U_EVENT_OBJ[iuyt];     
                }   
            }
            
            if ($U.isNull(obj)){
                if (vrecheck === true){
                } else{
                    setTimeout(function(){  //--**  화면로드등으로 인해 시간이 지체되는 경우 3초뒤 한번더 체크
                        $U.eventunbind(vobj, vEvent, vFunction, true);
                    },3000);                    
                } 
                return;
            } 
            
            if (obj === window){
                    obj.removeEventListener(vEvent.substring(2),vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
                    return;
            }
            
            if ($U.isNull(obj.length) || obj.length === 0){
                if (obj.removeEventListener){
                    obj.removeEventListener(vEvent.substring(2),vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
                } else {
                    if (obj[vEvent]){
                        obj[vEvent] =   null;
                    } else {
                        try{
                            obj.detachEvent(vEvent, vFunction);
                        } catch(e){
                        }
                    } 
                }
            } else {
                for (var q=0,eoobj;eoobj=obj[q];q+=1){
                    if (eoobj.removeEventListener){
                        eoobj.removeEventListener(vEvent.substring(2),vFunction, false );
                    } else {
                        if (eoobj[vEvent]){
                            eoobj[vEvent]   =   null;
                        } else {
                            try{
                                eoobj.detachEvent(vEvent, vFunction);
                            } catch(e){
                            }
                        } 
                    }
                }   
            }
        }

Upvotes: 0

Tejasva Dhyani
Tejasva Dhyani

Reputation: 1362

try this

$(document).ready(function(){

    $('.rem').click(function(){
        $('<a id="runtime" href="javascript:void(0);">runtime</a>').bind('click',func_name).appendTo("body");
    });
});//End of doc
function func_name(){
    alert('I got it!');
}

Since you are binding the object before it has been created, you are not getting the desired result.

Upvotes: 0

Chris Tonkinson
Chris Tonkinson

Reputation: 14469

Change

$('#runtime').bind('click',func_name());

to

$('#runtime').live('click',func_name); 

or (as of jQuery 1.7):

$('#runtime').on('click',func_name); 

Two things to note:

  1. I changed func_name() to func_name. You don't want to call the function when you bind the handler - you just want to reference it.
  2. Calling bind won't do you any good, because #runtime doesn't exist until after you've clicked .rem. That's why you need either live or on (depending upon your jQuery version).

And just for good measure: here's a good reference on why you should be using jQuery.on anyway.

Upvotes: 6

Kevin Ji
Kevin Ji

Reputation: 10499

You don't want to run the function at the point in the code, so remove the ():

$('#runtime').bind('click', func_name);

If you're using jQuery 1.7+, though, you should either use .on():

$('#runtime').on('click', func_name);

or use a .click() handler directly:

$('#runtime').click(func_name);

Upvotes: 3

Related Questions