【发布时间】:2016-11-27 16:43:18
【问题描述】:
我有一个带有子列表的列表和一个
我使用 ajax 获取新数据,然后删除列表,并将新元素(具有新数据的相同列表)注入 DOM。
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
var lista = $(data).find('#list-professores'); //Get only the new professor list and thier disciplines
$('#list-professores').remove(); //Remove old list
$('#professores').append(lista); //Append the new list where the old list was before.
load_js();
$('.prof-disciplinas').sortable({
connectWith: '.prof-disciplinas'});
}
});
});
</script>
问题是:当您向 dom 插入新元素时,您需要“重新加载”您的 javascript,以便它能够识别新元素。这就是我使用load_js() 方法所做的。
function load_js()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type = 'text/javascript';
script.src = 'js/script.js';
head.appendChild(script);
}
但是我在同一个 .php 文件中有另一个 <script > ... </script> 我需要重新加载它,以便它可以与这个新列表一起使用:
我需要重新加载脚本并在新列表中使用 Drag&Drop
<script type="text/javascript">
$(function(){
var oldTeacherId;
$('.prof-disciplinas').sortable({
connectWith: '.prof-disciplinas',
start: function (event, ui){
oldTeacherId = ui.item.parent().prev().prev().attr('data-id');
},
stop: function (event, ui){
$.ajax({
type: "POST",
url: '{{ URL::to("/professor") }}',
data: {
disciplina: ui.item.attr('data-id'),
professor: ui.item.parent().prev().prev().attr('data-id'),
old: oldTeacherId
},
success: function(data){
swal("Good job!", "You clicked the button!", "success");
//Atualizar tabela aqui
var evento = $('#calendario').fullCalendar('clientEvents', function(event){
return event.id == $(ui.item).attr('data-id');
});
evento[0].backgroundColor = '' + getCor( ui.item.parent().prev().prev().attr('data-id'));
$('#calendario').fullCalendar('updateEvent', evento[0]);
},
error: function(){
}
});
}
});
});
</script>
这种拖放效果在 ajax 之后不起作用。
我怎样才能重新加载那段脚本?让它识别并使用新插入的列表?
【问题讨论】:
标签: javascript jquery ajax dom