简体   繁体   English

JQuery append在JQuery单击函数中不起作用

[英]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”之后和新页面加载之前立即在RichText编辑器中添加徽标。

$('#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. 就像我点击“Go”一样,在加载新页面之前,图像会短暂出现在编辑器中。 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! 紧跟在追加行之后,会打印出img标签!

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. 有趣的是,当我在控制台中复制/粘贴相同的代码然后按“Go”时,一切正常,我可以看到图像,文本,无论我放在编辑器中。

I am using the latest Google Chrome for my labors. 我正在使用最新的谷歌浏览器来完成我的工作。

You are racing your async get method and next page load. 您正在竞争异步get方法和下一页加载。 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: 你可能应该在你的点击处理程序中返回false并在你的get请求的成功回调中转到下一页(如果这是你想要的):

$('#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 此外,width和height属性不应具有“px”,而应仅为数值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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