JavaScript中方法使用总结

问题

在九号公园与运动之家的商品规格集处理过程中,当用户选中某一条规格时,需要将该规格当前信息(名称、价格、库存)展示到用户输入框,以便用户在此基础上进行修改。如果规格名称以字母开头的话,会出现错误。错误类型是:Uncaught ReferenceError: a123 is not defined,这个a123即为规格名称。但当规格名称为纯数字的时候则一切正常。

具体代码

函数定义
var targetItemId = 0;
function showFormatInfo(id, name, price, store) {
    targetItemId = id;
    $("#name").val(name);
    $("#price").val(price);
    $("#store").val(store);
}
函数调用
$("#td1").append("" +
                        "" +
                        "" + item.id + "" +//规格id
                        "" + item.name + "" +//规格名称
                        "" + item.price + "" +//价格
                        "" + item.store + "" +//价格
                        "" + status + "" +//当前状态
                        ""
                    )

函数触发

onclick='showFormatInfo(" + item.id + "," + item.name + "," + item.price + "," + item.store + ")'

解决

百度到JS问题Uncaught ReferenceError:XXXX is not defined,于是怀疑我的问题也出现在调用时候的格式问题。

首先,$("#td1").append()方法的参数是一个字符串,因此在函数调用的时候item.name将会被具体值代替:a123。

然后,当函数触发的时候,将以如下格式调用方法showFormatInfo(1,a123,2,3),此时,1,3,4参数作为值进行传递,而参数2将作为变量进行传递,该变量当然找不到。因此就会出现Uncaught ReferenceError: a123 is not defined

然后,我知道了参数2应该是字符串类型的。为了将参数2作为字符串类型,做了如下改变:

onclick='showFormatInfo(" + item.id + ",'" + item.name + "'," + item.price + "," + item.store + ")'

即将参数2使用单引号进行包裹,但会发生格式异常,如Uncaught SyntaxError: Unexpected token }

最终,我知道了参数2应该是字符串类型的。因此应如下调用:

onclick='showFormatInfo(" + item.id + ",\"" + item.name + "\"," + item.price + "," + item.store + ")'

总结

当函数传参的时候,若参数值是字符串类型的话,应用引号进行包裹。

你可能感兴趣的:(JavaScript中方法使用总结)