如何在循环生成元素的同时使用PHP中的jquery选择特定元素?

时间:2015-09-30 13:20:11

标签: javascript php jquery

首先,我是网络编程的新手。也就是说,如果你能以最容易理解的方式向初学者展示我,我将非常感激。 我试图使用jQuery从while循环生成的列表中选择和编辑。我想要的是当用户单击编辑链接并输入另一个可用成员时更新可用成员。 我的代码如下:

PHP

       //fetch all available staffs
    $queryedit =  mysql_query("SELECT * FROM staffs WHERE Avail = 'yes'");
       while($row = mysql_fetch_assoc($queryedit)):
       $avail_staffs = $row['name'];
       $id = $row['id']; ?>
        <h4><?php echo $avail_staffs; ?></h4>
         <!--form is the child of <a> -->
        <a href='#' class="edit-<?php echo $id; ?>">Edit
                 <!--Hidden form that appears when I want to edit Staffs->
           <form id="hidden_form" style="display:none;">
               <input type="text" class="staff-name" placeholder="Enter Staff name">
               <button id="edit-<?php echo $id?>">update</button>
           </form>
       </a>
           <?php endwhile ?> 

然后我尝试在jQuery中处理它们:

的jQuery

        $(".edit").click(function () {
          //display hidden form
         $(this).find('form').show();
         //when the previously hidden button is clicked, grab the value in the input field & send to update.php
         $(this).find('button').click(function () {
          var staffs = $("input=[class='staff_name']").val();
           $.post("internal/update.php",{staffs:staffs},function(data) {
             alert("Updated");
              }); 

           });
          });

但这只会更新名字。它只对第一个成员名称应用更改,即使我单击最后一个成员名称。

1 个答案:

答案 0 :(得分:0)

您可以这样做:

$(".edit").click(function () {
    //display hidden form
    $(this).find('form').show();
    //when the previously hidden button is clicked, grab the value in the input field & send to update.php
    $(this).find('button').click(function () {
        var input = []; // create a new empty array 

        $('#hidden_form').each($('input'), function(){ // loop over each of the inputs
            input.push($(this).val()); // grab input value and add it to the array
        });
        $.post("internal/update.php",{input:input},function(data) {
            alert("Updated");
        });
    });
});

Haven没有对它进行过测试,所以这里和那里可能存在一些问题。