2012-06-01 60 views
1

我有两个包含客户信息的下拉列表。 使用PHP for循环,我允许一次输入5个客户的详细信息。使用jQuery从php循环中选择元素的ID

for($i=1; $i<6; $i++) 
{ 
    echo "<tr><td><select id=\"customer_" . $i . "_class\"></select></td>"; 
    echo "<td><select id=\"customer_" . $i . "_age\"></select></td></tr>"; 
} 

现在我想以这样的方式来执行一个jQuery函数,如果,例如,customer_2_class变化,它执行了一些功能到其相应的customer_2_age。

$("#customer_?_clas").change(function() 
{ 
    //some function to execute on corresponding customer_?_age 
}); 
+0

什么是你的问题? – Jared

回答

2

添加类到您的<select>和移动ID到其他属性,如data

echo "<tr>"; 
echo "<td><select class=\"customer_class\" data-id=\"$i\"></select></td>"; 
echo "<td><select class=\"customer_age\" data-id=\"$i\"></select></td>"; 
echo "</tr>"; 

而在你的javascript:

$('.customer_class').change(function() { 
    var id = $(this).attr('data-id'); 
    // process customer_class with this id 
}); 
+0

除'data-id'属性之外,添加'id'属性不会在这里受到伤害,因为'id'选择器比常规属性选择器快得多。 –

+0

我喜欢使用类的属性(我没有在我的答案中提出这个建议的唯一原因就是你已经有了),但是我可能没有'data-id'属性,而是找到匹配的年龄选择'$(this).closest('tr')。find('。customer_age')'。 – nnnnnn

+0

谢谢你们, 现在你有了var id中的data-id。 如何使用该特定数据ID为customer_class执行函数? 对不起,这个新手的问​​题.. –

0
$('select'). 
    filter(function() { 
     return /^customer_[0-9]_class$/.test(this.id); // filter on select 
                 // based on id format 
    }) 
    . change(function() {        // binding change 
                 // to filtered select 
     var num = this.id.match(/\d/)[0];    // get numerical value 
                 // of select box on change 

     $('#customer_' + num + '_age')     // point to target select 
      .css('background', '#f00');    // do something 
    }); 

Working sample

+0

这是错误的$('select_'+ num +'_age')' –

+0

@Asado Qureshi检查答案和工作示例 – thecodeparadox