这是我的情况。我有一个选择框,它是使用 PHP 从数据库 SELECT 命令填充的。同一个选择国家的选择有一个 jQuery 事件绑定(bind)在它上面并且在改变时它会加载每个国家的旗帜。
$("#CountryA").change(function () {
var countryname = this.options[this.selectedIndex];
var fileExist = $.ajax({
url: './../theme/_images/flags/' + $.trim($(countryname).text()) + '.png',
type: 'HEAD',
error: function () {
$("#flag").html('<img src= "./../theme/_images/flags/notFound.png" />');
},
success: function () {
$("#flag").html('<img src= "./../theme/_images/flags/' + $.trim($(countryname).text()) + '.png" />');
}
});
})
这是PHP
<?php
while ($data = $connection->dbFetchArray($resultCountry)) {
if ($data["Description"] == @$_GET['country'])
echo "<option value='" . $data["Description"] . "' selected='selected'>" . $data["Description"] . "</option>";
else
echo "<option value='" . $data["Description"] . "'>" . $data["Description"] . "</option>";
}
?>
我还使用 php 设法记住了用户在提交之前选择的值。但是在用户提交表单后(我使用的是 PHP_SELF,所以我留在同一页面中)标志消失了。
我可以让功能在sumbit按钮之后再次执行吗?在页面加载或其他方面以便向用户显示所选国家/地区的国旗???
提前致谢!
======================编辑======================== ===
好的,非常感谢 augustknight 和所有花时间回复的人...:D
我对你的代码做了一些小改动,因为这些行
var country_name = $("#CountryA :selected").val();
set_country_flag_image(this.options[this.selectedIndex]);
给我一些奇怪的 HTMLOptionElement 而不是选定的名称。所以这里是最终的代码,以供将来引用。 :D 再次感谢!!!
$(function () {
// Initialize the flag to the selected country (could also be done server-side)
var country_name = $("#CountryA").val();
set_country_flag_image(country_name);
// Update the flag image when a country is selected
$("#CountryA").change(function () {
alert($("#CountryA").val());
set_country_flag_image($("#CountryA").val());
});
});
function set_country_flag_image(country_name) {
$.ajax({
url: './../theme/_images/flags/' + country_name + '.png',
type: 'HEAD',
error: function () {
$("#flag").html('<img src= "./../theme/_images/flags/notFound.png" />');
},
success: function () {
$("#flag").html('<img src= "./../theme/_images/flags/' + country_name + '.png" />');
}
});
}
最佳答案
我认为这就是您要找的。p>
$(function () {
// Initialize the flag to the selected country (could also be done server-side)
var country_name = $("#CountryA :selected").val();
set_country_flag_image( country_name );
// Update the flag image when a country is selected
$("#CountryA").change(function(){
set_country_flag_image(this.options[this.selectedIndex]);
});
});
function set_country_flag_image(country_name)
{
$.ajax({
url:'./../theme/_images/flags/'+country_name+'.png',
type:'HEAD',
error:
function(){
$("#flag").html('<img src= "./../theme/_images/flags/notFound.png" />');
},
success:
function(){
$("#flag").html('<img src= "./../theme/_images/flags/'+country_name+'.png" />');
}
});
}
关于php - 在更改和页面加载时执行 jQuery 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9831464/