简体   繁体   English

将html文件加载到页面后,脚本无法运行

[英]Script doesn't run after loaded a html file into a page

i have a problem with my page. 我的页面有问题。 When i click on a link on my page, it will load a external html inside a div in the page. 当我单击页面上的链接时,它将在页面的div内加载外部html。 the div with the id="div1". id为“ div1”的div。 (AJAX) (AJAX)

It works perfect. 完美的作品。

the external html-page which has been loaded includes a div with the id="rex" . 已加载的外部html页面包括一个id为“ rex”的div

My Problem is: 我的问题是:

i have a script, which must add content in the div (with the id="rex") i wrote the script in the external file, but it doesn't run. 我有一个脚本,该脚本必须在div中添加内容(带有id =“ rex”),我已在外部文件中编写了该脚本,但是该脚本无法运行。 probably i must write my script in the page and not in the external html-file. 可能我必须在页面中而不是在外部html文件中编写脚本。

here the script Number 3: 这是脚本编号3:

$('#rex').ready(function() {
    var url="genredetail.php";
    var activitydetail = sessionStorage.activitydetail;

    $.getJSON(url,function(json){
        $.each(json.genredetail,function(i,item){
            if(item.name == activitydetail){
                $('<p class="excerpt">' + item.beschreibung3 + '</p>').appendTo('#rex');
            }
        });
    });
});

This script must run when the external file (with the div id="rex") has been loaded. 加载外部文件(具有div id =“ rex”)时,必须运行此脚本。 But it doesn't :-( What can i do? Is the problem that the script runs before the page get the <div id="rex"> ? 但这不是:-(我该怎么办?脚本在页面获取<div id="rex">之前运行的问题吗?

Thanks in advance, and sorry my bad english :-S 在此先感谢,对不起我的英语不好:-S

A picture for more clearness 图片更清晰 在此处输入图片说明

the script number 1 makes the link. 脚本编号1建立了链接。 when i click on a link, the script number 2, let the site load in the div1. 当我单击链接时,脚本编号为2,让站点加载到div1中。 The script number 3 must fill the div="rex" with informations. 脚本编号3必须用信息填充div =“ rex”。 but it doesn't run. 但它没有运行。

try onload 尝试加载

$('div').on("load","#rex",function() {

do something

});

Try using setInterval, so it check the element rex every 0.5 s 尝试使用setInterval,因此它每0.5秒检查一次元素rex

var myInterval = setInterval(function(){
            if ($("#rex").length)
            {
                var url="genredetail.php";
                var activitydetail = sessionStorage.activitydetail;

                $.getJSON(url,function(json){
                $.each(json.genredetail,function(i,item){
                if(item.name == activitydetail){

                $('<p class="excerpt">' + item.beschreibung3 + '</p>').appendTo('#rex');
                clearInterval(myInterval);
            }
    }, 500);

You need to reload the script if it is already loaded. 如果脚本已经加载,则需要重新加载。 As you said you are loading the external html inside a div, does it include the external js file you are using? 如您所说,您正在div中加载外部html,它是否包括您正在使用的外部js文件? if not please include it. 如果没有,请包括在内。

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

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