我正在尝试从对象中引用discount_code
属性,但是我一直收到以下错误。我如何访问discount_code
?
错误:
未捕获的TypeError:无法调用未定义的方法'val'
HTML:
<input type="text" name="txt_discount_code" value="12345" />
JS:
var cart = {
transaction: {},
discount_code: $('input[name=txt_discount_code]'),
get_cart_items_params: {
page: 'checkout',
s_method: 'get-cart-items',
txt_discount_code: this.discount_code.val()
// txt_discount_code: cart.discount_code.val()
}
};
答案 0 :(得分:6)
与ShankarSangoli
类似,您无法在定义对象之前访问该对象。
你必须将cart
的声明分成两部分:
var cart = {
transaction: {},
discount_code: $('input[name=txt_discount_code]')
};
cart.get_cart_items_params = {
page: 'checkout',
s_method: 'get-cart-items',
txt_discount_code: cart.discount_code.val()
};
或者只是将discount_code
放入变量:
var $discount_code = $('input[name=txt_discount_code]');
var cart = {
transaction: {},
discount_code: $discount_code
get_cart_items_params = {
page: 'checkout',
s_method: 'get-cart-items',
txt_discount_code: $discount_code.val()
}
};
答案 1 :(得分:2)
在完全定义之前,您无法使用该对象。它永远不会奏效。
答案 2 :(得分:1)
我最初认为你的问题在你的jQuery选择器上撒谎,但在我用jQuery选择器替换静态值并尝试引用它仍然无效。我得出结论,在完成对象的创建之前,你不能引用discount_code:
查看FIDDLE
var cart = {
transaction: {},
get_cart_items_params: {
page: 'checkout',
s_method: 'get-cart-items',
txt_discount_code: function(){
return $('input[name="txt_discount_code"]').val();
}
}
};
cart.get_cart_items_params.txt_discount_code();