我尝试从对象内引用 discount_code
属性,但不断收到以下错误。我如何访问discount_code
?
错误:
Uncaught TypeError: Cannot call method 'val' of undefined
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()
}
};
最佳答案
就像 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()
}
};
关于javascript - 属性(property)范围问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8248264/