我试图从对象内引用discount_code
属性,但我一直得到以下错误。如何访问discount_code
HTML:未捕获的类型错误:不能调用未定义的方法'val'
<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()
}
};
就像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()
}
};
在对象完全定义之前不能使用它。
我最初认为你的问题在于你的jQuery选择器,但在我替换了jQuery选择器的静态值,并尝试引用它仍然没有工作。我得出的结论是,在完成对象的创建之前,不能引用discount_code:
查看
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();