我正在从外部HTML文件中将一些复选框拉到选项卡容器中,加载后我希望它们按字母顺序排序。当复选框在内部加载时,排序工作正常,但是当从外部加载时,排序失败。不知道这是延迟问题还是其他错误。我已尝试过delay(),setTimeout()和来自相关帖子的提示,但没有任何效果。任何人的想法?小提琴:https://jsfiddle.net/cfan1L61/
https://code.jquery.com/jquery-1.12.4.js
https://code.jquery.com/ui/1.12.1/jquery-ui.js
<ul class="tabs-nav">
<li class="tab-active"><a href="#Container" rel="nofollow">Countries</a></li>
<li class=""><a href="#blank2" rel="nofollow">Year</a></li>
<li class=""><a href="#blank3" rel="nofollow">Products</a></li>
</ul>
<div class="TabContainerClass">
<div id="Container">
<div id="CountryID" class="CountryClass">
<!--
<label class="myEuropeCountries"><input type="checkbox" id="UN400" value="Poland" />Poland</label>
<label class="myEuropeCountries"><input type="checkbox" id="UN500" value="Macedonia" />Macedonia</label>
<label class="myEuropeCountries"><input type="checkbox" id="UN196" value="Cyprus" />Cyprus</label>
<label class="myEuropeCountries"><input type="checkbox" id="UN100" value="Bulgaria" />Bulgaria</label>
<label class="myEuropeCountries"><input type="checkbox" id="UN40" value="Austria" />Austria</label>
-->
</div>
</div>
</div>
// Loading from external file & sorting alphabetically
$(function() {
$.get('https://c2amf323.caspio.com/dp.asp?AppKey=3eb840009ff57a1cf3434759be01', function(data) {
var $data = $(data);
$("#CountryID").html($data.find('#CountryStore_ws'));
});
function sortByText(a, b) {
return $.trim($(a).text()) > $.trim($(b).text()) ? 1 : -1;
}
var li = $(".CountryClass").children("label").detach().sort(sortByText);
$(".CountryClass").append(li)
});
// ================
$(function() {
$('.tabs-nav a').on('click', function(event) {
event.preventDefault();
$('.tab-active').removeClass('tab-active');
$(this).parent().addClass('tab-active');
$('.TabContainerClass > div').hide();
$($(this).attr('href')).fadeIn(300)
});
$('.tabs-nav a:first').trigger('click');
});
.tabs-nav {
list-style: none;
margin: 0;
padding: 0;
}
.tabs-nav .tab-active a {
cursor: default;
}
.tabs-nav a {
border-width: 0px 1px 1px 0px;
border-style: solid;
display: block;
height: 32px;
text-align: center;
width: 160px;
}
.tabs-nav li {
float: left;
}
.TabContainerClass {
width: 480px;
height: 110px;
border: 1px solid orange;
clear: both;
position: relative;
background: white;
}
.CountryClass {
position: absolute;
width: 468px;
height: 80px;
}
答案 0 :(得分:2)
您应该将排序代码放到jquery success
回调函数
$.get( "ajax/test.html", function(data) {
// your code here
});
在你的情况下:
$(function() {
function sortByText(a, b) {
var first = $.trim($(a).text());
var second = $.trim($(b).text());
return first.localeCompare(second);
}
$.get('https://c2amf323.caspio.com/dp.asp?AppKey=3eb840009ff57a1cf3434759be01', function(data) {
var $data = $(data);
var sortedEl = $data.find('#CountryStore_ws').children("label").sort(sortByText);
$("#CountryID").append(sortedEl);
});
});