2017-05-08 100 views
0

如何使用html來觸發用javascript編寫的頁面加載和單擊複選框時的切換功能?javascript和html onclick&onload函數

本質上,該功能所做的是切換用戶的某個輸入框。我允許他們輸入定製價格。我希望此框可以默認顯示,也可以切換。我目前只能用這個輸入「onclick」工作,但是當我添加「onload」時,它默認不會加載。是的,我仍然可以點擊它來切換它。

<input 
type="checkbox" 
id="item_use_custom_price_<?php echo $_item->getId() ?>" 
checked="checked" 
onload="toggleCustPrice(order, this);" 
onclick="toggleCustPrice(order, this);" 
/> 

我有一個PHTML文件(不是一個真正的PHP問題)上面的輸入。該ID從PHP中拉出,網格可能有很多行。

我不認爲我可以使用window.onload()函數,因爲在我的JS腳本中,因爲我需要能夠將「順序」和「這個」參數傳遞到函數中,所以正確的行切換。

+1

沒有'的複選框onload'事件...... – Rayon

+0

有''元素上的'onload'事件是你打算使用的嗎?雖然如果功能是「默認顯示並點擊切換」,那麼你不應該使用任何'onload'事件。只需要將頁面狀態(樣式)初始化爲您想要的狀態即可。 – David

+0

我可以使用這裏的數據加載嗎? http://stackoverflow.com/questions/3708850/is-there-an-onload-event-for-input-elements – camdixon

回答

0

您在關於使用在this SO answer中演示的數據加載的評論中問了一句,我的答案是肯定的。還有其他方法可以解決這個問題,但現在的瀏覽器現在幾天都是最簡單的方法來完成你想要做的事情。

假設你不需要切換區分,如果你可以將多個切換在以後的頁面上意味着你希望他們所有的切換,你可以做這樣的事情:

<!-- You will just grab this by its name --> 
<input type="checkbox" ... data-name-you-want-here=""/> 

如果您需要一個可行的辦法在未來區分這些,你可以使用這種方法:

<!-- Add the unique ID you already have as the value --> 
<input type="checkbox" ... data-name-you-want-here="<?php echo $_item->getId() ?>"/> 

現在你只需要弄清楚你將如何調用這個代碼,並觸發切換。如果你需要向後兼容,你可以使用jQuery,但真的我認爲你可以使用vanilla JavaScript和querySelector()querySelectorAll()。如果你知道只有一個頁面使用的數據選擇:

var element = document.querySelector('name-you-used-here'); 
/* Now you have the element in JavaScript so toggle it */ 

與此同時,如果你有多個然後使用:所以在香草的JavaScript pseudocode

var element = document.querySelectorAll('name-you-used-here'); 
/* Now you have the element in JavaScript, loop and toggle accordingly */ 

這就是我看待它的工作。該功能只會通過將呼叫你的頁面的頁腳或在某種文件準備功能添加到它的調用被稱爲:

function doToggle(){ 
    var elem = [Do Query Selector Here] 

    ...Your toggle code here. 
    elem.id <--- If you need to pull out the ID 

    ...loop and use your toggle code if you used querySelectorAll 
}