javascript生成的对象在出现后立即消失

Objects generated by javascript vanish right after appearing

本文关键字:消失 对象 javascript      更新时间:2023-09-26

单击按钮时,我正在调用python脚本,并将结果填充到数组中。完成后,我创建<a href>与数组长度一样多的<a href>对象。问题是,一旦显示链接,它们就会立即消失。

Body:
//I obviously get the same effect by putting the onclick event in the submit button
window.onload = function() {
    alert("loaded");
    document.getElementById('submit_searchsubs').onclick = function () { 
        FindSubtitles();
    };
};
function FindSubtitles() {
        postData = {"movie": "Outlander", "season":"1", "episode":"2"};             
            $.ajax({
                url: "/cgi-bin/find_subtitles.py",
                type: "post",
                datatype:"json",
                async : false,
                data: {postData},
                success: function(response){
                    var subs = new Array();
                    var json = $.parseJSON(response);
                    for (var i=0;i<json.length;++i) {
                        subs[i] = new Array(json[i].IDSubtitle, json[i].SeriesEpisode, json[i].SubHash, json[i].SubDownloadsCnt, json[i].SeriesSeason, json[i].ZipDownloadLink, json[i].MovieName, json[i].id, json[i].SubFileName);
                    }
                    DisplaySubtitles(subs); //show the users the new words found in this subtitle
                } 
            })
            .fail(function(err) {
                alert("error" + err);
            });
    }
function DisplaySubtitles(subs) {
        var SubtitleDiv = document.getElementById("SubtitleDiv");
        var a = document.createElement('a');
        for (i = 0; i < subs.length; i++) {
            var linkText = document.createTextNode(subs[i][8]);
            a.appendChild(linkText);
            SubtitleDiv.appendChild(a);
        }
}

那么会发生什么:

  1. 页面加载
  2. alert("loaded"(在 window.onload 中触发时显示
  3. 查找字幕运行
  4. 显示字幕运行和<a>链接出现
  5. <a>链接消失,警报("已加载"(再次显示。

我不知道我是否应该使用 async: true ,因为在这种情况下我会收到[Object object]错误,这很奇怪,因为在另一个脚本的情况下我使用它,否则它会冻结 UI。

有什么想法吗?

正如 Kieveli 提到的,如果submit_searchsubs是一个提交的表单按钮,则可能会在提交后刷新页面。 尝试使用返回假;以绕过默认的浏览器单击操作。

document.getElementById('submit_searchsubs').onclick = function () { 
    FindSubtitles();
    return false;
};