2017-01-17 56 views
0

在一个“创造”页面中,我有很多的东西与复选框发生时选中或未选中其中之一,使用...如何在页面加载时运行更改功能?

$('.option').on('change', function() { 
//lots of stuff 
}); 

我有一个“编辑”页面上的这些复选框所以当“编辑”页面加载时,它会正确设置所有复选框(选中或取消选中),但也有一些数学计算是在页面加载时完成的。换句话说,当编辑页面第一次打开时,显示的数字是正确的,我需要上面的“更改”功能在页面加载时运行。

这样可行吗?基本上希望它在页面加载时运行,然后每当有实际的“更改”(如最初的预期)时再次运行。

+1

http://api.jquery.com/trigger/可能是这样的$( “选项”),触发器( “变化”) – Searching

回答

0

我将会分离逻辑:

$('.option').on('change', function() { 
    doLotOfStuff(); 
}); 

function doLotOfStuff() { 
    // do your stuff here 
} 

$(document).ready(function loadPage() { 
    doLotOfStuff(); 
}); 

这使得即使到extend你(如果需要的话)的逻辑,并通过在每一种情况下通过不同的PARAMS(再次,如果需要的话)重用。

0

将你的//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>