javascript和html onclick&;加载函数

javascript和html onclick&;加载函数,javascript,html,Javascript,Html,如何使用html在页面加载和单击复选框时启动javascript编写的切换函数 基本上,该函数所做的是为用户切换某个输入框。我允许他们输入自定义价格。我希望此框在默认情况下显示,并进行切换。我目前只能用“onclick”处理这个输入,但是当我添加“onload”时,默认情况下它不会加载。是的,我仍然可以单击它来切换它 <input type="checkbox" id="item_use_custom_price_<?php echo $_item->getId() ?&g

如何使用html在页面加载和单击复选框时启动javascript编写的切换函数

基本上,该函数所做的是为用户切换某个输入框。我允许他们输入自定义价格。我希望此框在默认情况下显示,并进行切换。我目前只能用“onclick”处理这个输入,但是当我添加“onload”时,默认情况下它不会加载。是的,我仍然可以单击它来切换它

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

你在一篇关于使用数据加载的评论中问到了这一问题,我的回答是肯定的。还有其他方法可以解决这个问题,但在当今的现代浏览器中,这是实现您的目标的最简单的方法

假设您不需要区分切换,也就是说,如果将来在页面上放置多个切换,您希望它们都切换,您可以执行以下操作:

<!-- You will just grab this by its name -->
<input type="checkbox" ... data-name-you-want-here=""/>
同样,如果您有多个,请使用:

var element = document.querySelectorAll('name-you-used-here');
/* Now you have the element in JavaScript, loop and toggle accordingly */
所以在香草JavaScript中,我认为它是这样工作的。只需将调用放在页面的页脚中,或在某种文档就绪函数中添加对该函数的调用,即可调用该函数:

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 
}
函数doToggle(){
var elem=[Do Query Selector Here]
…您的切换代码在这里。

elem.id没有复选框的
onload
事件…在
元素上有一个
onload
事件,这就是您想要使用的吗?尽管如果功能是“默认显示并点击切换”,那么您不需要使用任何
onload
事件。只需要页面状态(样式)最初是您想要的。我可以像这里一样使用数据加载吗?
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 
}