【问题标题】:Select element's id from php loop using jQuery使用 jQuery 从 php 循环中选择元素的 id
【发布时间】:2012-06-01 02:48:51
【问题描述】:

我有两个包含客户信息的下拉列表。 使用 PHP for 循环,我允许一次输入 5 个客户的详细信息。

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
});

【问题讨论】:

    标签: php javascript jquery select loops


    【解决方案1】:

    将类添加到您的 &lt;select&gt; 并将 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
    });
    

    【讨论】:

    • 除了data-id 属性之外,在这里添加id 属性不会有什么坏处,因为id 选择器比常规属性选择器快得多。
    • 我喜欢使用类属性(我没有在回答中建议它的唯一原因是你已经有了),但我可能会在没有 data-id 属性的情况下这样做,而是使用 $(this).closest('tr').find('.customer_age') 之类的东西找到匹配的年龄选择。
    • 谢谢大家,现在你在 var id 中有了 data-id。如何使用该特定数据 ID 为 customer_class 执行函数?对不起这个新手问题..
    • @AsadoQureshi 您应该使用更多 HTML/JS 代码创建一个新问题并解释您想要实现的目标。
    【解决方案2】:

    你可以使用attribute ends-with selector:

    $('select[id$="_class"]').change(function() {
    

    可能值得浏览full list of jQuery selectors

    【讨论】:

      【解决方案3】:
      $('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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-27
        • 1970-01-01
        • 2017-10-07
        • 1970-01-01
        • 2012-02-20
        • 2015-04-01
        • 1970-01-01
        • 2011-09-17
        相关资源
        最近更新 更多