简体   繁体   中英

JQuery append is not working inside a JQuery click function

So I am trying to append a logo in a RichText editor immediately after the user hits "Go" and before the new page loads.

$('#Go').on('click', function (e) {
    e.preventDefault();
    $.get(url, function(data) {
        var html = '<img src="' + data + '" width=100px height=100px></img>';
        $('.EditorFrame').contents().find('body').append(html);
    });
});

Just as I hit "Go", the image briefly appears in the editor before the new page is loaded. The new page - which shows nothing but the result of our editing comes out blank ! I have tried this with plain text as well - same story.

I have tried hard to debug. For instance, putting:

console.log($('.EditorFrame').contents().find('img'));

immediately after the append line, does print out the img tag!

Interestingly, when I copy/paste the same code in the console and then press "Go", everything works as normal and I can see the image, text whatever I put in the editor.

I am using the latest Google Chrome for my labors.

You are racing your async get method and next page load. You probably should return false in your click handler and go to the next page (if that's what you desire) in the success callback of your get request:

$('#Go').on('click', function (e) {
    e.preventDefault();
    $.get(url, function(data) {
        var html = '<img src="' + data + '" width="100" height="100"></img>';
        $('.EditorFrame').contents().find('body').append(html);
        // go to next page here
    });
    return false;
});

Also, width and height attributes should not have "px" and should just be numeric values

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