简体   繁体   中英

click event is not working for dynamically created button

I am using google translator which creates dynamically translator bar,it has show original button (click on below image link).

I want to fire click event of "show original" button manually using javascript or jquery but is is not working, see some of the code snippets that i tried.

$("#myBtn").click(function(){
    $("#\\:1\\.restore").click();
    //or
    $("#\\:1\\.restore").on('click');
    //or
    $("#\\:1\\.restore").trigger('click',jQuery.Event( "click" ));
    //or
    document.getElementById(':1.restore').click();
})

imageURL: http://1drv.ms/1KhfLbo

The event on myBtn is not fired and your event handler is not working. For dynamically added elements use event delegation .

$(document).on('click', '#myBtn', function() {
    // Your Code Here
});

To trigger event:

$("#\\:1\\.restore").trigger('click');

You need delegate from a container such as document

$(document).on('click', '#\\:1\\.restore', function(){...}));

I want to fire click event of "show original" button manually

Use

$('#\\:1\\.restore').trigger('click')

or

$('#\\:1\\.restore').click();//with no parameters

I got the answer. Actually translate bar was inside iframe tag, so we need to select iframe (container) then any element inside that.

$("#myBtn").click(function(){
    $('#\\:1\\.container').contents().find('#\\:1\\.restore').click(); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM