jQuery在下一个多重选择框中选择所有选项

| 我有几种形式,需要使用一些多选框。 (会员列表,来源列表,产品列表等)。每种表格都可以具有自己的一组多框框,无论我的客户需要什么。 我还创建了一个链接,该链接允许用户在任何多选框内“全选”选项。到目前为止,一切正常!但是我想使jQuery更加智能。 这是我编写的示例:
<table>
    <tr>
        <td><div id=\"allaffs\" class=\"selectAll\">select all</div></td>
    </tr>
  <tr>
    <td>
    <select name=\"affid[]\" id=\"affid\" size=\"15\" style=\"width:230px;height:300\" multiple=\"multiple\">
      <option value=\"0\" selected=\"selected\">--no affiliate assigned--</option>
        <? while($r = mysql_fetch_array($somequerystuff)){  ?>
      <option value=\"<?php echo $r[\'affid\']; ?>\" selected=\"selected\"><?php echo $r[\'affname\']; ?></option>
      <? } ?>
    </select>   
    </td>
  </tr>
</table>

<table>
    <tr>
        <td><div id=\"allsources\" class=\"selectAll\">select all</div></td>
    </tr>
  <tr>
    <td>
    <select name=\"sourceid[]\" id=\"sourceid\" size=\"15\" style=\"width:230px;height:300\" multiple=\"multiple\">
      <option value=\"0\" selected=\"selected\">--no source assigned--</option>
        <? while($r = mysql_fetch_array($somequerystuff)){  ?>
      <option value=\"<?php echo $r[\'sourceid\']; ?>\" selected=\"selected\"><?php echo $r[\'sourcename\']; ?></option>
      <? } ?>
    </select>   
    </td>
  </tr>
</table>

<script language=\"javascript\" type=\"text/javascript\">
$(document).ready(function(){

  $(\".selectAll\").click(function(){
    var theID = $(this).attr(\'id\');
    if(theID==\'allaffs\'){ $(\"#affid option\").attr(\"selected\",\"selected\"); }
    if(theID==\'allsources\'){ $(\"#sourceid option\").attr(\"selected\",\"selected\"); }
  });

});
</script>
这完全有效。但是出于其他过滤原因,我倾向于添加更多的多框。 我想让jquery检测到.selectAll类的click事件,但要使其足够聪明以在下一个可用的多框中选择所有选项。这样,我就不必在jquery代码中为新框创建新行。     
已邀请:
        与其将其基于位置(下一个可用的多框),不如将其用作数据属性来存储相关多框的ID。
<div class=\"selectAll\" data-multi-id=\"sourceid\">select all</div>
然后在您的脚本中:
<script language=\"javascript\" type=\"text/javascript\">
    $(document).ready(function(){  
        $(\".selectAll\").click(function(){    
            var multi = $(this).data(\'multi-id\');
            $(\'#\' + multi + \' option\').attr(\'selected\', \'selected\');
        });
    });
</script>
    
        对我来说,一种巧妙的方法是将
<select multiple=\"multiple\">
框包装起来,并将其“全选”在特定的父元素(例如
div
)中,然后使用.parent()
<html>
<head>
  <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js\"></script>
</head>
<body>
  <div>
    <span class=\"selectAll\">Select all</span>

    <select multiple=\"multiple\">
      <option>1</option>
      <option>2</option>
    </select>
  </div>

  <div>
    <span class=\"selectAll\">Select all</span>

    <select multiple=\"multiple\">
      <option>1</option>
      <option>2</option>
    </select>
  </div>

  <span class=\"selectAll\">Select really all</span>

  <script>
    $(\".selectAll\").click(function () {
      $(this).parent().find(\'option\').attr(\'selected\',\'selected\');
    });
  </script>
</body>
</html>
    

要回复问题请先登录注册