我们如何只加载一次jquery函数

How we load the jquery function only one time

本文关键字:一次 jquery 函数 加载 我们      更新时间:2023-09-26

我只想让我的jQuery函数只运行一次。目前我使用的是国家,州/城市下拉。所以当用户选择任何国家时,它会显示城市/州。但最初它没有显示任何东西,所以我调用document.ready。但问题是,每次都是先显示乡村城市。有没有解决办法。或者你能推荐其他国家吗?城市按下拉列表。

下拉菜单的代码是

function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
var x, i=0;
for(x in country_arr){
    option_str.options[i++] = new Option(country_arr[x],country_arr[x]);
}
}
function print_state(state_id, state_index){
var option_str = document.getElementById(state_id);
var x, i=0; state_index++;
var state_arr = s_a[state_index].split("|");
for(x in state_arr){
        option_str.options[i++] = new Option(state_arr[x],state_arr[x]);
}
}

您还可以修改它,以便在页面加载时默认显示第一个国家的城市。由于

现在你应该使用jQuery了

function print_country(country_id){
  // given the id of the <select> tag as function argument, it inserts <option> tags
  var countrySel = $("#"+country_id);
  // create a "singleton" by returning if the state exists
  if (countrySel.size() > 1) return;
  $.each(country_arr,function() {
      countrySel.append('<option value="'+$(this)+'">'+$(this)+'</option>');
  });
  // call it with the second option (assuming "Please select")
  // change to ,0 for first option
  print_state("state", 1); 
}
function print_state(state_id, state_index){
  var stateSel = $("#"+state_id);
  var state_arr = s_a[state_index].split("|");
  $.each(state_arr,function() {
    stateSel.append('<option value="'+$(this)+'">'+$(this)+'</option>');
  });
}