jQuery .on()函数没有按预期工作

时间:2016-07-28 16:33:28

标签: javascript jquery html

我有工作jQuery,根据所选项目的数量添加计数,问题是我有多个选择器和多个计数显示字段。我不太清楚为什么这不起作用。

当我更改1时,它会更改所有选择的计数。

/*Account Group Count*/
$( 'body' ).on('change', $('#group-accounts'),function() {
    var strAccount = $( "select option:selected" ).length;
    $( ".AccountCount" ).text( strAccount );
    $( ".AccountSmallCount" ).text( strAccount + ' selected');
});

/*User Group Count*/
$( 'body' ).on('change', $('#group-users'),function() {
    var strUser = $( "select option:selected" ).length;
    $( ".UsersCount" ).text( strUser );
    $( ".UsersSmallCount" ).text( strUser + ' selected');
});

以下是其中一个选择

<div class="ui-multiselect col-full group-accounts-select">                 
        <select name="group-accounts" id="group-accounts" multiple>
            <cfloop query="AccountGroupList">
                <option value="<cfoutput>#AccountGroupList.aprimID#</cfoutput>"><cfoutput>#aName#</cfoutput></option>
            </cfloop>                   
        </select>
        <label for="group-accounts"><span>Accounts:</span></label>
    </div>
    <span class="AccountSmallCount"></span>

1 个答案:

答案 0 :(得分:2)

/*Account Group Count*/
$(document).on('change', '#group-accounts', function(){ // <-- the difference 
    var strAccount = $(this).find(":selected").length;
    $( ".AccountCount" ).text( strAccount );
    $( ".AccountSmallCount" ).text( strAccount + ' selected');
});

/*User Group Count*/
$(document).on('change', '#group-users', function(){ // <-- the difference 
    var strUser = $(this).find(":selected").length;
    $( ".UsersCount" ).text( strUser );
    $( ".UsersSmallCount" ).text( strUser + ' selected');
});

你就是这样做的(代表团):

//[root element]    [event]   [target selector] [callback]  
  $(  document ).on('change', '#group-users',   function(){..}