在我的PHP页面上,我使用AJAX来获取拍卖的项目,当从下拉列表中选择某些内容时,一切正常(如图1 所示)。我的问题是,当页面第一次加载时(见第二张图片)比没有发生任何事情,我只想将下拉列表的默认值加载到Ajax中,就像其他的一样,我该怎么办围绕这个问题?请注意,在第一张图片中我首先选择了其他内容,然后再次选择了默认值,第二张图片是我打开浏览器时没有其他操作的页面。
我的代码:
$(function() {
$("#filtercatselect").on("change", function() {
var categoryid = document.getElementById("filtercatselect").value;
var orderbyname = document.getElementById("filterorderbyselect").value;
if(categoryid == "")
{
categoryid = 0;
}
$.post('homefiltering.php', { catid: categoryid, sortname: orderbyname }, function(result) {
$('#item-container').html(result);
}
);
});
$("#filterorderbyselect").on("change", function() {
var categoryid = document.getElementById("filtercatselect").value;
var orderbyname = document.getElementById("filterorderbyselect").value;
if(categoryid == "")
{
categoryid = 0;
}
$.post('homefiltering.php', { catid: categoryid, sortname: orderbyname }, function(result) {
$('#item-container').html(result);
}
);
});
});
答案 0 :(得分:0)
只需将代码置于此代码下,即可在首次执行脚本时触发change
事件
[--- your code above ---]
$("#filterorderbyselect").trigger('change');
// OR - based on what code you prefer to execute on first page execution
// place both you make two equal ajax calls- thanks to Don't Panic
$("#filtercatselect").trigger('change');
答案 1 :(得分:0)
这个怎么样?在加载时,您调用我给出的名称的函数,然后将它们分配给下拉列表中的change-event。
$(document).ready(function(){
// call these methods on load
filtercatselectChangeHandler();
filterorderbyselectChangeHandler();
// set on-change handlers
$("#filtercatselect").change(filtercatselectChangeHandler);
$("#filterorderbyselect").change(filterorderbyselectChangeHandler);
});
function filtercatselectChangeHandler(){
var categoryid = document.getElementById("filtercatselect").value;
var orderbyname = document.getElementById("filterorderbyselect").value;
if(categoryid == "")
{
categoryid = 0;
}
$.post('homefiltering.php', { catid: categoryid, sortname: orderbyname }, function(result) {
$('#item-container').html(result);
}
);
}
function filterorderbyselectChangeHandler(){
var categoryid = document.getElementById("filtercatselect").value;
var orderbyname = document.getElementById("filterorderbyselect").value;
if(categoryid == "")
{
categoryid = 0;
}
$.post('homefiltering.php', { catid: categoryid, sortname: orderbyname }, function(result) {
$('#item-container').html(result);
}
);
}