【问题标题】:How to also run a change function on page load?如何在页面加载时也运行更改功能?
【发布时间】:2017-05-31 23:44:49
【问题描述】:
在“创建”页面上,当复选框中的一个被选中或未选中时,我会使用...
$('.option').on('change', function() {
//lots of stuff
});
我在“编辑”页面上也有这些复选框,因此当“编辑”页面加载时,它会正确设置所有复选框(选中或未选中),但我还需要完成一些数学计算 onchange在页面加载。换句话说,要在第一次打开编辑页面时显示正确的数字,我需要上面的“更改”功能在页面加载时运行。
这可行吗?基本上希望它在页面加载时运行,然后在有实际“更改”时再次运行(如最初预期的那样)。
【问题讨论】:
标签:
javascript
jquery
checkbox
onchange
【解决方案1】:
我会分开逻辑:
$('.option').on('change', function() {
doLotOfStuff();
});
function doLotOfStuff() {
// do your stuff here
}
$(document).ready(function loadPage() {
doLotOfStuff();
});
这甚至允许 extend 您的逻辑(如果需要),并通过在每个案例上传递不同的参数来重用它(再次,如果需要)。
【解决方案2】:
将您的//lots of stuff 包装在一个函数中。在事件 ready 使用 one() 方法调用您的 //lots of stuff 一次。在此代码段中,我创建了一个名为 process() 的函数,它仅在 DOM 为 ready 时调用一次,并且在复选框位于 change 下的任何时候调用。
片段
/* When document is ready call on...
|...process() only once.
*/
$(document).one('ready', process);
// Any change on any checkbox call process()
$('.chx').on('change', process);
function process(e) {
var total = 0;
$(".chx:checked").each(function() {
total += parseInt($(this).val(), 10);
});
$('#total').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<label>1
<input class='chx' type='checkbox' value='1'>
</label>
<label>2
<input class='chx' type='checkbox' value='2'>
</label>
<label>3
<input class='chx' type='checkbox' value='3'>
</label>
<label>4
<input class='chx' type='checkbox' value='4' checked>
</label>
<label>5
<input class='chx' type='checkbox' value='5'>
</label>
<label>6
<input class='chx' type='checkbox' value='6'>
</label>
<label>7
<input class='chx' type='checkbox' value='7' checked>
</label>
<label>8
<input class='chx' type='checkbox' value='8'>
</label>
<label>9
<input class='chx' type='checkbox' value='9'>
</label>
<label>10
<input class='chx' type='checkbox' value='10' checked>
</label>
</fieldset>
<label for='total'>Total:
<output id='total'></output>
</label>