【问题标题】:Running Javascript function after variables are set设置变量后运行 Javascript 函数
【发布时间】:2010-02-12 10:34:54
【问题描述】:

我有以下功能:

// NATION
var x, y, z;
function flag(nation,area)
{
x = nation;
this.nation=nation;
var el=document.getElementById("desc");
el.innerHTML='The region you have selected is <b>'+area+'</b>';
document.getElementById("flag").innerHTML='<img src="images/flags/'+nation+'.jpg">';
}
// SERVICE
function output(service)
{
y = service;
this.service=service;
var el=document.getElementById("service-desc");
el.innerHTML='You have selected a <b>'+service+'</b> service.';
document.getElementById("clock").innerHTML='<img src="images/clock-'+service+'.png">';
}

一旦用户设置了变量:nation & service 已经设置,那么我想运行这个函数:

function selectmodel()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support XMLHTTP!");
  return;
  }
var location=x;
var time=y;
var weight=z;
var url="selectmodel.php";
url=url+'?location='+location+'&time='+time+'&weight='+weight;
xmlhttp.onreadystatechange=stateChanged1;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
window.location.hash="slider";
}
function stateChanged1()
{
if (xmlhttp.readyState==4)
  {
  document.getElementById("result").innerHTML=xmlhttp.responseText;
  }
}

请有好心人告诉我该怎么做?

谢谢, B.

编辑 - 抱歉忘了说变量来自 onclick 的 (onClick="flag('scotislands', 'Scottish Islands');")

【问题讨论】:

    标签: javascript function variables isset equivalent


    【解决方案1】:

    我猜你正在寻找——以真正的 Javascript 精神——寻找某种被触发的事件,也许甚至有办法,但在这种情况下,我只是从每个函数中调用一个检查:

    var x = null;
    var y = null;
    var ...
    
    function trySelectModel() {
      if (x == null) || (y == null) return;
      selectModel(); // Your function
    }
    
    function flag(...) {
      // Your existing code
      trySelectModel();
    }
    
    function output(service) {
      // Your existing code
      trySelectModel();
    }
    
    function selectmodel() {
      // Your existing code
    }
    

    【讨论】:

    • 嗨,如果 (x == null) || (y == null) 返回;不说如果 null 就运行?
    • 不,如果其中一个或两个变量为空,则它会跳出函数,即在这种情况下永远不会调用 selectModel 行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多