JavaScript 事件无法识别我的函数

javascript event doesn't recognize my function

本文关键字:我的 函数 识别 事件 JavaScript      更新时间:2023-09-26

我有一个用于设置用户位置的 ajax 脚本,表单输入是一个

<select id="region" onchange="city('/ajax-city.php')" ...>
   <option>
<select ..'>
   <option...>

当第一个选择列表中的选项之一发生更改 (onchange( 时,将向服务器发送 AJAX 请求,并处理响应并更新第二个<select>

这是用于更新<select>的函数

var city = function(page)
{
    if(xhro){ // stands for Xml Http Request Object
      var fv = document.getElementById('region').value;
      var obj = document.getElementById('city-element');
      obj.innerHTML="<span style='"display:block; width:200px; float:right; padding:0 10px 10px 0; font-family:Tahoma; font-size:12px;'"> please wait.. </span>";
      xhro.open("POST",page);
      xhro.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
      xhro.onreadystatechange = function()
      {
        if(xhro.readyState==4 && xhro.status==200)
        {
            obj.innerHTML = "<select name='"city'"  onchange='"subcity('ajax-subcity.php')'" id='"city'" >"+xhro.responseText+"</select>";
        }
      }
      xhro.send("city=" + fv);
}

如您所见,我的函数添加了onchange属性,以便在触发<select name="city"> onchange事件时发送另一个ajax请求,但是当我单击<select name="city">中的下一个选项时,在Firebug的控制台中,我收到此错误

subcity is not a function

subcity("ajax-subcity.php");

当我在控制台中键入函数时,Firebug 识别它,我认为当 ajax 请求更新 DOM 元素时,事件不会像页面正常加载时那样处理。

但这只是一个建议,考虑city()处理和更新的功能<select name="city>"但在下一个级别(subcity()(没有更新发生

创建<option ..>是用PHP脚本完成的。

它认为问题不在于 subcity(( 函数,因为它在火虫 BTW 中工作,很高兴被提及。

var subcity = function(page){
alert("problem solved");
if(xhro){
    var fv = document.getElementById('city').value;
    var obj = document.getElementById('subcity-element');
    obj.innerHTML="<span style='"display:block; width:200px; float:right; padding:0 10px 10px 0; font-family:Tahoma; font-size:12px;'"> please wait</span>";
    xhro.open("POST",page);
    xhro.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhro.onreadystatechange = function(){
        if(xhro.readyState==4 && xhro.status==200){
            obj.innerHTML = "<select name='"subcity'" id='"subcity'" >"+xhro.responseText+"</select>";
        }
    }
    xhro.send("city=" + fv);
}

我引用:

   if(xhro.readyState==4 && xhro.status==200){
            obj.innerHTML = "<select name='"subsity'" id='"subcity'" >"+xhro.responseText+"</select>";
        }

更改您在选择中使用的子城市ID,请使用"子城市"而不是">子城市",否则它将覆盖您的子城市功能!!

ids被JavaScript使用,这就是为什么它们必须是唯一的,它不仅仅是CSS。

编辑:

对城市和城市功能执行相同的操作

PS:你的代码一团糟,认真的!修复它。