2011-11-23 45 views
0

我试图从对象内引用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() 
    } 
}; 
+1

这在我看来,'$(“输入[名称= txt_discount_code]')'不起作用。也许你应该从那里调试。 – hafichuk

+0

如果我尝试用'alert($('input [name = txt_discount_code]')。val());'给它加上正确的结果,所以我不确定为什么它不起作用前面的上下文。 – Donnie

+0

只是用选择器替换你的'this.discount_code.val()'。 – hafichuk

回答

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

我最初相信,你的问题在你的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(); 
2

不能使用对象是完全确定之前。它永远不会工作。