development

DOM에 아직 추가되지 않은 JQuery 객체에 클릭 이벤트 첨부

big-blog 2020. 6. 2. 08:11
반응형

DOM에 아직 추가되지 않은 JQuery 객체에 클릭 이벤트 첨부


이 질문에는 이미 답변이 있습니다.

클릭 이벤트를 DOM에 추가하기 전에 JQuery 객체에 연결하는 데 많은 문제가있었습니다.

기본적으로 내 함수가 반환하는이 버튼이 있고 DOM에 추가합니다. 내가 원하는 것은 자체 클릭 핸들러로 버튼을 반환하는 것입니다. 핸들러에서 첨부하기 위해 DOM에서 선택하고 싶지 않습니다.

내 코드는 다음과 같습니다

createMyButton = function(data) {

  var button = $('<div id="my-button"></div>')
    .css({
       'display' : 'inline',
       'padding' : '0px 2px 2px 0px',
       'cursor' : 'pointer'
     }).append($('<a>').attr({
       //'href' : Share.serializeJson(data),
       'target' : '_blank',
       'rel' : 'nofollow'
     }).append($('<image src="css/images/Facebook-icon.png">').css({
       "padding-top" : "0px",
       "margin-top" : "0px",
       "margin-bottom" : "0px"
     })));

     button.click(function () {
        console.log("asdfasdf");
     });

     return button;     
}

리턴 된 단추가 클릭 이벤트를 포착 할 수 없습니다. 그러나이 작업을 수행하면 (버튼이 DOM에 추가 된 후) :

$('#my-button').click(function () {
    console.log("yeahhhh!!! but this doesn't work for me :(");
});

그것은 ...하지만 내가 원하는 것이 아니라 나를 위해 작동하지 않습니다.

객체가 아직 DOM의 일부가 아니라는 사실과 관련이있는 것 같습니다.

오! 그건 그렇고, OpenLayers로 작업하고 있으며 버튼을 추가 할 DOM 객체는 OpenLayers.FramedCloud입니다 (DOM의 일부는 아니지만 일단 두 개의 이벤트가 트리거됩니다).


이것을 사용하십시오. dom ready에 존재하는 부모 요소로 body를 바꿀 수 있습니다

$('body').on('click', '#my-button', function () {
     console.log("yeahhhh!!! but this doesn't work for me :(");
});

on ()이 1.7 이상으로 live ()를 대체 할 때 on ()을 사용하는 방법에 대한 자세한 내용은 http://api.jquery.com/on/ 을 참조 하십시오 .

아래에 사용해야하는 버전이 나와 있습니다.

$ (selector) .live (이벤트, 데이터, 핸들러); // jQuery 1.3 이상

$ (document) .delegate (선택자, 이벤트, 데이터, 핸들러); // jQuery 1.4.3 이상

$ (document) .on (이벤트, 선택기, 데이터, 핸들러); // jQuery 1.7 이상


아직 아무도 이것을 게시하지 않은 것에 놀랐습니다.

$(document).on('click','#my-butt', function(){
   console.log('document is always there');
}) 

해당 페이지에 어떤 요소가 있을지 확실치 않은 경우에 첨부하십시오 document.

Note: this is sub-optimal from performance perspective - to get maximum speed one should try to attach to the nearest parent of element that is going to be inserted.


Try this.... Replace body with parent selector

$('body').on('click', '#my-button', function () {
    console.log("yeahhhh!!! but this doesn't work for me :(");
});

Try:

$('body').on({
    hover: function() {
        console.log("yeahhhh!!! but this doesn't work for me :(");
    },
    click: function() {
        console.log("yeahhhh!!! but this doesn't work for me :(");
    }
},'#my-button');

jsfiddle example.

When using .on() and binding to a dynamic element, you need to refer to an element that already exists on the page (like body in the example). If you can use a more specific element that would improve performance.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Src: http://api.jquery.com/on/


You have to append it. Create the element with:

var $div = $("<div>my div</div>");
$div.click(function(){alert("clicked")})
return $div;

Then if you append it will work.

Take a look at your example here and a simple version here.


On event

$('#my-button').on('click', function () {
    console.log("yeahhhh!!! but this doesn't work for me :(");
});

Or add the event after append


Complement of information for those people who use .on() to listen to events bound on inputs inside lately loaded table cells; I managed to bind event handlers to such table cells by using delegate(), but .on() wouldn't work.

I bound the table id to .delegate() and used a selector that describes the inputs.

e.g.

HTML

<table id="#mytable">
  <!-- These three lines below were loaded post-DOM creation time, using a live callback for example -->
  <tr><td><input name="qty_001" /></td></tr>
  <tr><td><input name="qty_002" /></td></tr>
  <tr><td><input name="qty_003" /></td></tr>
</table>

jQuery

$('#mytable').delegate('click', 'name^=["qty_"]', function() {
    console.log("you clicked cell #" . $(this).attr("name"));
});

Does using .live work for you?

$("#my-button").live("click", function(){ alert("yay!"); }); 

http://api.jquery.com/live/

EDIT

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

http://api.jquery.com/on/


jQuery .on method is used to bind events even without the presence of element on page load. Here is the link It is used in this way:

 $("#dataTable tbody tr").on("click", function(event){
    alert($(this).text());
 });

Before jquery 1.7, .live() method was used, but it is deprecated now.


Maybe bind() would help:

button.bind('click', function() {
  alert('User clicked');
});

참고URL : https://stackoverflow.com/questions/10920355/attaching-click-event-to-a-jquery-object-not-yet-added-to-the-dom

반응형