我使用的是Semantic UI 2.1,但我遇到了问题。我的页面中有三个滑块复选框。它们都有相同的类,我可以一次初始化它们。它们每个都包含一个data-*
属性,我需要通过AJAX调用将其发送到服务器。
问题在于:
第一次完成AJAX调用后,复选框的事件不再起作用。我知道事件是绑定到DOM的,并且随着DOM的更改它们不会更新但是有什么方法可以解决它吗?
这是我页面的一个非常简单的版本:
<html>
<body id="body">
<!-- First Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="0" type="checkbox"> <label></label>
</div>
<!-- Second Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="2" type="checkbox"> <label></label>
</div>
<!-- Third Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="3" type="checkbox"> <label></label>
</div>
<button class="button-action">Do Stuff</button>
</body>
<script>
$('.checkbox.comment').checkbox().checkbox({
onChecked: function () {
// This is only called before ajax reload, after ajax, it just won't
console.log("onChecked called");
},
onUnchecked: function () {
// This too is only called before ajax reload
console.log("onUnchecked called");
}
});
$(document).delegate('.button-action', 'click', function () {
$.ajax({
// Noraml ajax parameters
})
.done(function (data) {
if (data.success) {
// Reload
$('#body').load(document.URL + ' #body');
}
});
});
</script>
<html>
答案 0 :(得分:0)
您可以尝试将复选框事件侦听器放在函数中,并在每次重新加载页面或在文档DOM中进行更改时调用该函数。我在下面附上了一个示例代码供参考。
function Checkbox_eventlistener(){
$('.checkbox.comment').checkbox().checkbox({
onChecked: function () {
// This is only called before ajax reload, after ajax, it just won't
console.log("onChecked called");
},
onUnchecked: function () {
// This too is only called before ajax reload
console.log("onUnchecked called");
}
});
}
$(document).delegate('.button-action', 'click', function () {
$.ajax({
// Noraml ajax parameters
})
.done(function (data) {
if (data.success) {
// Reload
$('#body').load(document.URL + ' #body');
Checkbox_eventlistener();
}
});
});
$(function(){
Checkbox_eventlistener();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.js"></script>
<!-- First Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="0" type="checkbox"> <label></label>
</div>
<!-- Second Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="2" type="checkbox"> <label></label>
</div>
<!-- Third Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="3" type="checkbox"> <label></label>
</div>
<button class="button-action">Do Stuff</button>