2012-03-05 42 views
0

我有我的頁面上的字段orit_c_discountrate的ID我需要一個onlcick調用另一個JavaScript函數命名UpdateQuotedPrice我有這個下面寫了這個領域後,添加圖像:的Javascript追加圖標到現場

function AddPercentImage(){ 
    var img = document.createElement('IMG'); 
    img.setAttribute('src', 'Themes/Img/default/icons/recent_order.gif'); 
    img.onclick = function(){ 
      UpdateQuotedPrice(); 
     } 
    //This is the line that errors 
    document.getElementById('orit_c_discountrate').appendChild(img) 
} 

並使用此的attachEvent

window.attachEvent("onload",AddPercentImage); 

但我得到以下錯誤控制檯

SCRIPT65535:意外調用方法或屬性訪問。

元素:

<input name="orit_c_discountrate" class="EDIT" id="orit_c_discountrate" type="text" size="4" maxLength="4"/> 

誰能告訴我什麼,我做錯了什麼?

感謝

+0

哪行代碼導致此錯誤? – ManseUK 2012-03-05 16:57:58

+0

抱歉,我的壞,appendChild錯誤 – 2012-03-05 17:02:27

+0

Works here> http://jsfiddle.net/eNnWv/ < - 沒有問題(除了圖像不存在!!)...你確定你有一個ID與一個元素'orit_c_discountrate'。你能包含你的HTML嗎? – ManseUK 2012-03-05 17:05:59

回答

3

您不能將圖像追加爲input的子元素......你可以換你一個<span>內輸入(或作爲div另一種元素如)和圖像追加到。對於例如:

HTML:

<span><input name="orit_c_discountrate" class="EDIT" id="orit_c_discountrate" type="text" size="4" maxLength="4"/></span>​ 

的JavaScript:

function AddPercentImage() { 
    var img = document.createElement('IMG'); 
    img.setAttribute('src', 'Themes/Img/default/icons/recent_order.gif'); 
    img.onclick = function() { 
     UpdateQuotedPrice(); 
    }; 
    //This is the line that errors 
    document.getElementById('orit_c_discountrate').parentNode.appendChild(img); 
} 

Working demo

+0

真棒謝謝這個效果很好 – 2012-03-05 17:16:45

+0

@JustinErswell沒有probs ... – ManseUK 2012-03-05 17:17:07