Javascript 动态加载数据并执行js的jQuery函数?
例如,我们有两个php页面(同一个域):Javascript 动态加载数据并执行js的jQuery函数?,javascript,jquery,Javascript,Jquery,例如,我们有两个php页面(同一个域): index.php php(使用jQuery脚本) 如果我在“index.php”中加载“data.php”的一部分,我必须从“data.php”中重新执行js文件,如下所示: $( ".box" ).load("data.php .my_data", function() { $.getScript("https://website.com/js/data.js"); }); 是否有其他/更好的方法从external data.php加载部件
- index.php
- php(使用jQuery脚本)
$( ".box" ).load("data.php .my_data", function() {
$.getScript("https://website.com/js/data.js");
});
是否有其他/更好的方法从external data.php加载部件并自动执行与其连接的所有js?data.php
(此模板不包含脚本)
选项2:在用于加载模板的事件之外写入事件
$('.box').load('data.php').done(function (template) {
$(template).appendTo('body');
});
$(document).on('click', 'button', function () {
console.log('clicked!');
});
这种方法需要所有处理data.php
的脚本都在index.php
上准备好
如果不想移动/拆分代码:
data.php
:
<div class="template">
<div class="title">
<span>Title</span>
</div>
<div class="content">
<span>Content</span>
</div>
<div>
<button type="button">Read</button>
</div>
</div>
<script src="/js/data.js"></script>
在index.php
上,添加模板后,代码将正常工作。没有什么比这更重要了
$('.box').load('data.php').done(function (template) {
$(template).appendTo('body');
});
$(document).on('click', 'button', function () {
console.log('clicked!');
});
<div class="template">
<div class="title">
<span>Title</span>
</div>
<div class="content">
<span>Content</span>
</div>
<div>
<button type="button">Read</button>
</div>
</div>
<script src="/js/data.js"></script>
// this code works imediately after your document has `.load` class
$(document).on('click', '.load', function () {
// this code will work if your document already has `.box` class
$('.box').load('some_data.php').done(function (template) {
console.log(template);
});
});