JavaScript 在 AJAX 加载的 DIV 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4476064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:34:46  来源:igfitidea点击:

JavaScript not working inside AJAX loaded DIV

javascriptjqueryajax

提问by ihab

I am having a problem getting the javascript code to work inside an AJAX loaded div, I am trying to include jquery tabs but it not working, the ajax outputs text only and won't recognize the javascript. Any help would be nice.

我在让 javascript 代码在 AJAX 加载的 div 中工作时遇到问题,我试图包含 jquery 选项卡但它不起作用,ajax 仅输出文本并且无法识别 javascript。你能帮忙的话,我会很高兴。

Here is my js code:

这是我的js代码:

var OpenedPage;

function load(url, target) {
    document.getElementById(target).innerHTML = 'Loading ...';
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (req != undefined) {
        req.onreadystatechange = function () {
            loadDone(url, target);
        };
        req.open("GET", url, true);
        req.send("");
    }
}

function loadDone(url, target) {
    if (req.readyState == 4) { // only if req is "loaded"
        if (req.status == 200) { // only if "OK"
            document.getElementById(target).innerHTML = "loaded" + req.responseText;
        } else {
            document.getElementById(target).innerHTML = "Error:\n" + req.status + "\n" + req.statusText;
        }
    }
}

function unload() {
    if (OpenedPage == "divsignin") {
        unloaddivsignin();
    }
    if (OpenedPage == "divHowto") {
        unloaddivHowto();
    }

}

function ShowHidedivsignin() {
    unload();
    OpenedPage = "divsignin";
    load("../slogin.php", "divsignin");
    $("#divsignin").animate({"height": "toggle"}, {duration: 800});
}

function unloaddivsignin() {
    OpenedPage = "";
    $("#divsignin").animate({"height": "toggle"}, {duration: 800});
}

function ShowHidedivHowto() {
    unload();
    OpenedPage = "divHowto";
    load("../howto.php", "divHowto");
    $("#divHowto").animate({"height": "toggle"}, {duration: 800});
}

function unloaddivHowto() {
    OpenedPage = "";
    $("#divHowto").animate({"height": "toggle"}, {duration: 800});
}

And the HTML:

和 HTML:

<div id="divsignin" style="display:none;width:auto"> </div>


<a onClick="ShowHidedivHowto(); return false;" href="#">help</a>

采纳答案by Basic

I haven't checked all your code but what are you using to trigger the javacript loaded into your div? the window/document ready functions will only fire once when the page is initially loaded...

我还没有检查你所有的代码,但是你用什么来触发加载到你的 div 中的 javacript?窗口/文档就绪功能只会在页面最初加载时触发一次...

Try the something like the following for the content loaded into the div...

为加载到 div 中的内容尝试类似以下内容...

<div id="tabs">
    <ul>
        <li><a href="#fragment-1"><span>One</span></a></li>
        <li><a href="#fragment-2"><span>Two</span></a></li>
        <li><a href="#fragment-3"><span>Three</span></a></li>
    </ul>
    <div id="fragment-1">
        <p>First tab is active by default:</p>
        <pre><code>$('#example').tabs();</code></pre>
    </div>
    <div id="fragment-2">
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
    </div>
    <div id="fragment-3">
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
    </div>
</div>
<script type="text/javascript">
    $("#tabs").tabs();
</script>

Note the script tag is at the end so it will be parsed after the tabs are loaded.

请注意,脚本标记在末尾,因此将在加载选项卡后对其进行解析。

The alternative would be to modify the function called when AJAX is successful and add

另一种方法是修改 AJAX 成功时调用的函数并添加

 $("#tabs").tabs();

to the end of it - again this will make sure the code runs only after the contents have been loaded.

到最后 - 这将再次确保代码仅在加载内容后运行。

回答by karim79

Since you are already using jQuery, you should start refactoring that to be more readable and therefore more maintainable. Notably, you can ditch that load function, and incorporate a pattern similar to this:

由于您已经在使用 jQuery,您应该开始重构它,使其更具可读性,因此更易于维护。值得注意的是,您可以放弃该加载功能,并采用类似于以下的模式:

$(document).ready(function() {

    // <a class="help" href="help.html">help</a>
    $("a.help").live("click", function() {
        $("#divHowTo").html("Loading...");
        $.ajax({
            url: "../howto.php",
            dataType: "html",
            success: function(html) {
                $("#divHowTo").html(html)
                    .animate({"height": "toggle"}, { duration: 800 });
            }
        });
        return false;
    });
});

回答by Gyaneshwar kumar

I think you need this :Try executing script with jquery rather than with innerHTML:

我认为你需要这个:尝试使用 jquery 而不是 innerHTML 执行脚本

Instead of this :

而不是这个:

document.getElementById("content").innerHTML="<script>alert();</script>";

Try this:

尝试这个:

$("#content").html("<script>alert();</script>");