动态创建按钮以由选择器调用

时间:2012-11-30 04:56:32

标签: jquery ajax

伙计们我有一个创建动态按钮的ajax,每个按钮的id都有一个计数器。我试图选择每个按钮并为它们添加一个类。

   var html;
                $.ajax({
                          type:'POST',
                          url:'add_subject.php',
                     dataType:'json',
                         data:{'func_numbr':'6'},
                      success:function (data){
                           var counter_sub = 0 ;
                         $.each(data, function(i, item) {
                          if(data[i].subjct_statu == "0"){
                            $('#inactivate['+counter_sub+']').addClass("inactiveButton");
                           }
                          html = "<tr>";

                          html += "<td><lable>Subject: </label><input type='text' name='subject["+counter_sub+"]' rel='"+data[i].subj_id+"' value='"+data[i].subj_name+"'></td>";
                          html += "<td><input type='button' id='activate["+counter_sub+"]' name='active' class='button active  ' value='Apply'  > ";
                          html += "<input type='button' id='inactivate["+counter_sub+"]' name='active' class='button inactive' value='Remove from list'></td>";
                          html += "</tr>";
                 $('#curr-4thhigh-tble').append(html);

                 counter_sub = counter_sub +1;
                });
                      }     
               });

但是我正在做的事情不起作用我想有些事情是错的。 plss help tnx in advanced

2 个答案:

答案 0 :(得分:0)

尝试这样的事情,应该有效:

$.ajax({
    type: 'POST',
    url: 'add_subject.php',
    dataType: 'json',
    data: {
        'func_numbr': '6'
    },
    success: function(data) {
        var counter_sub = 0,
            classToAdd = "";
        $.each(data, function(i, item) {
            classToAdd = "";
            if (data[i].subjct_statu == "0") {
                classToAdd = "inactiveButton";
                //$('#inactivate[' + counter_sub + ']').addClass("inactiveButton");
            }
            html = "<tr>";

            html += "<td><lable>Subject: </label><input type='text' name='subject[" + counter_sub + "]' rel='" + data[i].subj_id + "' value='" + data[i].subj_name + "'></td>";
            html += "<td><input type='button' id='activate[" + counter_sub + "]' name='active' class='button active  ' value='Apply'  > ";
            html += "<input type='button' id='inactivate[" + counter_sub + "]' name='active' class='button inactive " + classToAdd + "' value='Remove from list'></td>";
            html += "</tr>";
            $('#curr-4thhigh-tble').append(html);
            counter_sub = counter_sub + 1;
        });
    }
});​

答案 1 :(得分:0)

我会建议将类添加到它们中,因为它们的创建方式与其他注释/答案建议一样。但是..回答你的问题,这就是你如何选择id为“myID”的所有元素

       $("[id*='+myID+']")

或循环

        $("[id*='+myID" + counter_sub + "']")