简体   繁体   English

从先前加载的jquery脚本引用动态加载的事物

[英]referencing dynamically loaded things from a previously loaded jquery script

let's say that i have something like this: 假设我有这样的事情:

<head><script src="script1.js" ...></script></head>
<body><div id="div1"></div></body>

which i call index.html, and div1's content is loaded dynamically, like 我称之为index.html,并且div1的内容是动态加载的,例如

$("#div1").html ("div1.html");

where div1.html is something like 其中div1.html类似于

<div id="div2"><canvas id="canv1" ... /></div>

and i want to reference canv1 somehow in script1.js; 我想在script1.js中以某种方式引用canv1; by just operating on $("#canv1") nothing happens because script1.js is loaded before div1.html; 仅通过在$(“#canv1”)上进行操作就不会发生任何事情,因为script1.js div1.html 之前加载; is there a way (eg $(document).on(...)) to "do something as soon as [..] is loaded"? 有没有办法(例如$(document).on(...))“ [..]加载后立即执行某些操作”? i tried 我试过了

$(document).on ("load", "#canv1", ...);

but it doesn't work. 但这不起作用。 it's worth noticing that $(document).on ("click", "#canv1", ...) works, but it's not what i want (as in, i want to draw something in the canvas before caring of what happens on click...); 值得注意的是$(document).on(“ click”,“#canv1”,...)可以工作,但这不是我想要的(例如,我想在画布上画一些东西,然后再关心发生的事情)点击...); any ideas? 有任何想法吗?

Presumably you're loading your content with a AJAX call, then doing your append in the callback. 大概是通过AJAX调用加载内容,然后在回调中进行添加。 If you put the $('#canv1')... after the append, within the callback, it should work. 如果将$('#canv1')...放在追加后的回调中,则它应该可以工作。

Edit based on the OP's comment below: 根据以下OP的评论进行编辑:

$.ajax (
    {url: "div1.html",
     cache: false}).
done (function (html){
    $("#div1").append (html);
    $("#canv1").click(...);
 });

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

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