HTML按钮,返回javascript为undefined。

时间:2015-11-18 00:35:36

标签: javascript jquery html scope undefined

我一直在尝试将以下内容执行到我正在处理的项目中。

简单地说,当我点击一个按钮时,我希望能够将一个列表项添加到它正上方。我定义的java脚本如下:

function CritHandoff(IDNumber, Description, Status) {
    this.IDNumber = IDNumber;
    this.Description = Description;
    this.Status = Status;
}

function AddCritHandoff() {    
    var result = '';
    var Temp = new CritHandoff("ID123456", "This is a description", "Active");
    result += $('#CritHandoff').html("<li>"+Temp.IDNumber+"</li>");
    return result;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

     <h1 class="Crit" style="color:red">Critical Handoff:</h1>

    <ul id="CritHandoff">
        
    </ul>
    <button type="button" onclick="AddCritHandoff()">Test</button>

当我尝试在页面加载后执行,然后单击按钮,调试器启动并说AddCritHandOff()未定义。但是,如果我这样更改代码

$(function AddCritHandoff() {    
    var result = '';
    var Temp = new CritHandoff("ID123456", "This is a description", "Active");
    result += $('#CritHandoff').html("<li>"+Temp.IDNumber+"</li>");
    return result;
});

结果将是在没有问题的情况下在页面加载上执行。

我的问题是:

这只是Scope的问题吗?虽然它提到对象是未定义的,但在我看来它是定义的,而不是在我点击按钮的时候。

我还能怎么做呢?

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

我切换。 html 到。追加,它确实有效。 - 希望这有帮助

function CritHandoff(IDNumber, Description, Status) {
  this.IDNumber = IDNumber;
  this.Description = Description;
  this.Status = Status;
}

function AddCritHandoff() {
  var result = '';
  var Temp = new CritHandoff("ID123456", "This is a description", "Active");
  result += $('#CritHandoff').append("<li>" + Temp.IDNumber + "</li>");
  return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="Crit" style="color:red">Critical Handoff:</h1>

<ul id="CritHandoff">

</ul>
<button type="button" onclick="AddCritHandoff()">Test</button>

答案 1 :(得分:0)

您正在使用jQuery对象连接String。我会这样做:

$(function(){
function CritHandoff(ID, description, status){
  this.ID = ID;
  this.description = description;
  this.status = status;
}
function addCritHandoff() {
  var crit = new CritHandoff("ID123456", "This is a description", "Active"), res = crit.ID;
  $('#CritHandoff').html('<li>'+res+'</li>');
  return res;
}
// I would have this as external JavaScript and run the onclick here as well after giving your button an id or something
});

由于传统原因,我做了一些改变。