2

我想添加一个成功和失败的功能,但我该怎么做呢?我在下面有这段代码:

    class ={};

    class.hey = function(values)
    {
      document.getElementById(values.id).innerHTML = values.Val ;

    return class;
    }



    class.hey({
    id:"target",
    Val: "hello world",//this wil work and will display that value in the span tag
    })

<span id="target"></span>//here will appear the value passed before

我如何添加一个函数来告诉我一切是否正常?我一直在尝试,但我无法解决这个 id 是如何工作的示例

    class ={};

    class.hey = function(values)
    {
      document.getElementById(values.id).innerHTML = values.Val ;

    return class;
    }



    class.hey({
    id:"objetive",//the element does not exist
    Val: "hello world",//this wil work and will display that value in the span tag
    success:function(msg)
        {
 alert("ok!")

},

     error:function(msg){
      alert("wrong");
   }
    })

<span id="target"></span>//here will appear the value passed before
4

1 回答 1

3

这对 JavaScript 来说根本不是自动的,但你可以这样做:

class.hey = function (value) {
    var value = document.getElementById(values.id);
    if (!value) {
        value.error(values.id + " is not an element")
        return false;
    }
    value.innerHTML = values.val;
    value.success("okay!");
}
于 2013-03-02T00:26:48.680 回答