2012-10-20 5 views
2

모두 안녕에 난복사 onclick 이벤트

이 일을 어떤 방법이 있는지 그것이 가능 나를 인도 해주십시오이

$('#ElementId').attr('OldOnClick',$('#ElementId').attr('OnClick')); 

같은 요소의 온 클릭 이벤트를 복사하는 것입니다 흥미로운 질문이 있습니다 이.

난 내가 다른 속성의 이름으로 자신의 onclick을 저장하려고 그래서 그들을 복구해야 어떤 점에서와 다른 점에 양식에있는 모든 요소의 클릭 이벤트를 해제하려고

+0

정확히 무엇을하려는가요? 위와 같이 속성을 복사해도 작동하지 않아도되는 이유는 없습니다. 그것이 무엇이든하기를 기대하는 것은 완전히 다른 이야기입니다. 또한 인라인 핸들러를 피해야합니다. –

+0

어떤 시점에서 양식에있는 요소의 모든 클릭 이벤트를 사용하지 않으려 고하고 다른 속성 이름과 함께 해당 onclick을 저장하려고 할 때 다른 지점에서 복구해야합니다. – rahul

+0

제공된 접근 방식을 사용하여 시도해 보셨나요? 예로서? –

답변

3

그래, 당신이 할 수있는 액세스 핸들러 기능 이 것 JQuery와에 그것을하는 방법 :

$('#specialbutton').click(function(){ console.log("peaches");}; 

var handlerFunction = $('#specialbutton').data("events").click[0].handler; 

$('#specialbutton').click(); // "peaches" 
handlerFunction(); // "peaches" 

당신은 다음과 같은 다른 요소에 할당 것이다 : 당신은 아래에서 두 번째 줄을 나타나지 않을 수처럼

$('#otherelement').click(handlerFunction); 
$('#otherelement').click(); // "peaches" 
+0

diff를 사용하여 동일한 요소에 onclick 이벤트를 복사하려고합니다. 속성 이름 제 질문을 올바르게 읽으십시오. – rahul

+0

@rahul - 일단 .data ("events")를 사용하여 클릭 핸들러에 대한 핸들을 얻은 다음 [0] .handler'를 클릭하면 원하는 곳으로 복사 할 수 있습니다. 예를 들어'$ ('# specialbutton') 할 수 있습니다. 데이터 ('copied', handlerFunction); – techfoobar

+0

도 시도했지만 해당 요소의 onclick 이벤트가 발생했습니다 – rahul

0

소리가 난다. 복사본을 작성하는 동안 이동을 원할 것입니다.

$('#ElementId').attr('oldonclick', $('#ElementId').attr('onclick')) 
       .removeAttr('onclick'); 
0

다음은 요소의 데이터에서 "onclick"저장소를 제거하고 나중에 데이터에서 사용할 수 있도록합니다. 당신이 개별 내에서 뭔가를 변경하려면 A 태그

에게 DEMO http://jsfiddle.net/u4eVW/1/

/* remove "onclick" and store */ 
$('a').each(function() { 
    var onclick = $(this).attr('onclick') 
    $(this).data('oldClick', onclick) 
    $(this).removeAttr('onclick') 

}) 

/* initialize handlers from data */ 
$('a').click(function() { 
     eval($(this).data('oldClick')) 
}) 

를 사용하는 예는 "onclick을"당신은 문자열로 속성 값을 치료하고 수정하는 정규식 방법을 사용해야합니다.

<a href="#" onclick="alert('foo')"> Link 1</a> 

var onclick=$(selector).attr('onclick').replace('foo', 'bar') 
2

이벤트를 복사하기위한 jQuery 플러그인을 작성했습니다. 그러나 동적으로 추가 된 이벤트에서만 작동하지만 "on"기능으로 추가 된 이벤트에서는 작동하지 않습니다.

누군가에게 도움이되기를 바랍니다.

매개 변수 :

이벤트 유형 - "클릭", "마우스 오버"등

대상 - jQuery를 객체, DOM 요소 나 선택 중 하나

clearCurrent - 그것은 목적지에 현재의 핸들러를 취소 할 경우는 true - 기본값 false

(function($){ 
      $.fn.copyEventTo = function(eventType, destination, clearCurrent) { 
      var events = []; 
      this.each(function(){ 
       var allEvents = jQuery._data(this, "events"); 
       if (typeof allEvents === "object") { 
        var thoseEvents = allEvents[eventType]; 
        if (typeof thoseEvents === "object") { 
         for (var i = 0; i<thoseEvents.length; i++){ 
          events.push(allEvents[eventType][i].handler); 
         }   
        } 
       } 
      }); 
      if (typeof destination === "string") { 
       destination = $(destination); 
      } else if (typeof destination === "object") { 
       if (typeof destination.tagName === "string") { 
        destination = $(destination); 
       } 
      } 
      if (clearCurrent === true) destination.off(eventType); 
      destination.each(function(){ 
       for(var i = 0; i<events.length; i++) { 
        destination.bind(eventType, events[i]); 
       } 
      }); 
      return this; 
     } 
    })(jQuery);