2011-07-19 164 views
1

編輯: OK,我相信我已經找到了使用@ManseUK貼有@約翰的評論沿着信息解決此問題的方法。作爲一個n00b我不能回答我自己的問題,但我已經在問題的下面添加了一個解釋,以幫助其他人解決問題。JavaScript函數給出錯誤

I am re-writing part of an e-commerce solution which was written by another development team some years ago. In the new version, we are experimenting with shortening the user journey using Ajax but doing so gives JavaScript errors and causes some functions to fail. Dev URL is here:

http://cognition.thelightbulb.co.uk/type-18/general-purpose-lamps-and-bulbs/craftlight-daylight

The errors appear once the dropdowns have been selected and the product displays.

The errors are displaying most notably in IE7:

Error: 'frm.qty' is null or not an object 
Error: 'qty.value' is null or not an object 

I believe this is where the problem is coming from:

var frm = document.frmOrder; 
var qty = frm.qty; 

In the lines above, frmOrder is the name of the form and qty is the name of the input for product quantity.

Compare that to http://cognition.thelightbulb.co.uk/product-54 where the product loads without the Ajax selection process and you'll see that the functions work correctly.

I suspect that the problem is to do with the fact that var frm = document.frmOrder; is not working due to the way it relates to the DOM when loaded with Ajax.

I am using innerHTML=xmlhttp.responseText as the Ajax method. Is there an alternative way to define var frm so that it will function properly when loaded with Ajax?

編輯: 使用@ManseUK貼有@約翰的評論沿着信息,我添加了另一個參數CheckMinQty(minorder),以便它現在看起來像這樣...

function CheckMinQty(minorder,qty)

...其中qty傳遞給onclick事件的功能爲document.forms['frmOrder'].qty.value

然後我將整個功能移出一個單獨的.js文件。這可能不是最好的方法,但它仍然感覺Ajax調用返回可工作的HTML,其中CheckMinQty可以使用,而不是引入整個負載<script>,然後嘗試運行它。

感謝您提出的所有建議,並歡迎您對上述方法/解決方案提出任何意見。

回答

0

更改此

var frm = document.frmOrder; 

這個

var frm = document.forms['frmOrder']; 

這會給你一個句柄形式

+0

感謝您的建議@ManseUK,但我仍然得到'錯誤:'frm.qty'爲null或不是一個對象'當頁面加載。 –

0

document.frmOrder指元素與ID frmOrder的頁面,其上恰好是這個頁面上的表單。試着在那裏獲得正確的form-element作爲變量。

+0

謝謝@約翰,腳本在這裏工作得很好:http://cognition.thelightbulb.co.uk/product-54所以我認爲我有正確的表單元素。這只是使它與Ajax一起工作的一個例子 –

+0

好的,我看到你首先設置了frm變量(當頁面剛剛加載完成時),並在單擊事件時執行這些函數。不要太早設置frm-variable,只需在需要時獲取。不是最好的解決方案,但它應該工作。 – Johan

0

雖然Manse的解決方案可能會起作用,但使用更明智的方法併爲表單指定一個id,因爲無論如何您都使用jQuery,請使用var frm = $(#formid);檢索表單,它更容易編寫由你和其他人閱讀。

0

當通過AJAX加載腳本時,您再也沒有DOMReady事件。換句話說,當您想要在AJAX加載時執行腳本時,應該使用自調函數。 包裝你的AJAX加載腳本這樣的函數內部:

(function(){ 
    // Do what you want to do here. 
})(); 

看看是否能解決問題嗎?

+0

謝謝@Saeed,這似乎阻止了頁面加載時的任何錯誤。 'CheckMinQty(minorder)'仍然失敗。我想這是因爲它使用'qty.value'。 '函數CheckMinQty(minorder)'應該位於自調函數之外嗎? –