2016-07-28 45 views
-1

我有工作jQuery是添加一个计数取决于选定项目的数量,问题是我有多个选择器和多个计数显示字段。我不太清楚为什么这不起作用。jQuery .on()函数不能按预期工作

当我改变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> 
+3

请提供[MCVE] –

+3

为什么你传递jQuery对象,而不是只是选择器? –

+0

在做出这样简单的基本错误之前,请先阅读API。 – vsync

回答

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(){..} 
+1

您不是在这里委托事件。这与OP的代码 –

+0

不一样行为好的我会更改 – vsync

+1

谢谢@vsync – Charles