简体   繁体   English

如何在jQuery中单击相应按钮的表中的行记录

[英]how to get record of a row in table whose corresponding button is clicked in jQuery

I am working on Laravel project, I have some country information stored in database, using AJAX request I am retrieving record from database, and appending it in my HTML table, the rows(cells) of table are editable so, my main goal is to edit them and update them in database, issue I am facing is that, I have added onClick event on update button, but it is automatically called when loop is in progress , but when I click button manually it doesn't work , I want that relevant row record whose button is clicked so I can update it.我正在处理 Laravel 项目,我在数据库中存储了一些国家信息,使用 AJAX 请求我正在从数据库中检索记录,并将其附加到我的 HTML 表中,因此我的主要目标是可编辑的表(编辑它们并在数据库中更新它们,我面临的问题是,我在更新按钮上添加了 onClick 事件,但是当循环正在进行时它会自动调用,但是当我手动单击按钮时它不起作用,我想要那个单击按钮的相关行记录,以便我可以更新它。

demo screenshot演示截图在此处输入图像描述 HTML code HTML代码

<table class="table table-bordered table-responsive-md table-striped text-center" id="tblData">
        <thead>
            <tr>
                <th class="text-center">ID</th>
                <th class="text-center">Country Name</th>
                <th class="text-center">Region</th>
                <th class="text-center">Pressing Social Challenge</th>
                <th class="text-center">Ethnic Conflict</th>
                <th class="text-center">Civil Strife</th>
                <th class="text-center">Social Upheaval</th>
                <th class="text-center">Health Risk</th>
                <th class="text-center">SI SCORE</th>
                <th class="text-center">Update</th>
            </tr>
        </thead>
        <tbody id="mapDataRecord">

        </tbody>
    </table>

JS code JS代码

$(document).ready(function() {
    load_data();

});


function load_data()
{
    getRecords='getRecords';
    $.ajaxSetup({
        headers: 
        {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
        }
    });
    $.ajax({
        url:"getMapData",
        method:"POST",
        data:'getRecords='+getRecords,
        success:function(data)
        {
            // $('#mapDataRecord').html(data);
            var jsonData = JSON.parse(data);
            var dataAppend='';
            for (let index = 0; index < jsonData.length; index++) 
            {
                dataAppend+="<tr><td class='text-center font-weight-bold ids'>"+
                jsonData[index]['id']+"</td><td class='text-center font-weight-bold tester'>"+
                jsonData[index]['countryName']+"</td><td class='text-center font-weight-bold'>"+
                jsonData[index]['region']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['pressing_social_challenge']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['ethnic_conflict']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['civil_strife']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['social_upheaval']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['health_risk']+"</td><td class='text-center font-weight-bold'>"+
                getSiScore(jsonData[index])+"</td><td class='text-center'><button class='btn btn-primary' id='updateData' onclick='"+
                updateRecord(jsonData[index])+"'>Update</button></td></tr>";
            }
            $('#mapDataRecord').html(dataAppend);
            // console.log(jsonData[0]);
        }
    });
}

function getSiScore(array)
{
    var value = (array['pressing_social_challenge']*(10/100))+(array['ethnic_conflict']*(30/100))+(array['civil_strife']*(20/100))+(array['social_upheaval']*(20/100))+(array['health_risk']*(20/100));
    // return value;
    if(value>5)
    {
        return 5;
    }
    else
    {
        return value.toFixed(1);
    }
}

function updateRecord(data){
    console.log(data);
}

You should try to put an alert to see if the data are ok.您应该尝试发出警报以查看数据是否正常。

you button id is always 'updateData' maybe there is a probleme with it, like you click on it and then javascript try to find the object with this id but as they are many it could just answer 'undefined'.您的按钮 id 始终是“updateData”,也许它有问题,例如您单击它,然后 javascript 尝试使用此 id 找到 object,但由于它们很多,它只能回答“未定义”。

EDIT: you are calling updateRecord in your 'for' instead of putting the fonction inside the onClick, just take care of the quote and it should be OK编辑:您在“for”中调用 updateRecord 而不是将函数放在 onClick 中,只需注意报价,应该没问题

 for (let index = 0; index < jsonData.length; index++) 
            {
                dataAppend+="<tr><td class='text-center font-weight-bold ids'>"+
                jsonData[index]['id']+"</td><td class='text-center font-weight-bold tester'>"+
                jsonData[index]['countryName']+"</td><td class='text-center font-weight-bold'>"+
                jsonData[index]['region']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['pressing_social_challenge']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['ethnic_conflict']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['civil_strife']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['social_upheaval']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['health_risk']+"</td><td class='text-center font-weight-bold'>"+
                getSiScore(jsonData[index])+"</td><td class='text-center'><button class='btn btn-primary' id='updateData' onclick='updateRecord("+jsonData[index])+"'>Update</button></td></tr>";
            }


Should work应该管用

I'm trying to sort out the issue by doing few changes on the code:我试图通过对代码进行一些更改来解决问题:

    $(document).ready(function() {
    load_data();

});

var jsonData = {};

function load_data()
{
    getRecords='getRecords';
    $.ajaxSetup({
        headers: 
        {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
        }
    });
    $.ajax({
        url:"getMapData",
        method:"POST",
        data:'getRecords='+getRecords,
        success:function(data)
        {
            // $('#mapDataRecord').html(data);
            jsonData = JSON.parse(data);
            var dataAppend='';
            for (let index = 0; index < jsonData.length; index++) 
            {
                dataAppend+="<tr><td class='text-center font-weight-bold ids'>"+
                jsonData[index]['id']+"</td><td class='text-center font-weight-bold tester'>"+
                jsonData[index]['countryName']+"</td><td class='text-center font-weight-bold'>"+
                jsonData[index]['region']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['pressing_social_challenge']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['ethnic_conflict']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['civil_strife']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['social_upheaval']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['health_risk']+"</td><td class='text-center font-weight-bold'>"+
                getSiScore(jsonData[index])+"</td><td class='text-center'><button class='btn btn-primary' id='updateData' data-index='"+ index + "'>Update</button></td></tr>";
            }
            $('#mapDataRecord').append($(dataAppend));
            // console.log(jsonData[0]);
        }
    });
}

function getSiScore(array)
{
    var value = (array['pressing_social_challenge']*(10/100))+(array['ethnic_conflict']*(30/100))+(array['civil_strife']*(20/100))+(array['social_upheaval']*(20/100))+(array['health_risk']*(20/100));
    // return value;
    if(value>5)
    {
        return 5;
    }
    else
    {
        return value.toFixed(1);
    }
}

function updateRecord(index){
    console.log(jsonData[Number(index)]);
}

$(document).on('click', "#updateData", function () {
    console.log(jsonData(Number($(this).attr("data-index"))));
});
  1. Assigned jsonData variable outside if the function.如果 function,则在外部分配 jsonData 变量。
  2. Replaced $('#mapDataRecord').html(dataAppend);替换$('#mapDataRecord').html(dataAppend); with $('#mapDataRecord').append($(dataAppend));$('#mapDataRecord').append($(dataAppend));
  3. changed updateRecord function.更改了更新记录updateRecord

EDIT: Removed the click event from inside the for loop and added a common click event.编辑:从 for 循环中删除了点击事件并添加了一个常见的点击事件。 You can apply same logic on your originally posted code.您可以对最初发布的代码应用相同的逻辑。

updateRecord function automatically runs because you are actually caling the function with this line "updateRecord(jsonData[index])" . updateRecord function 会自动运行,因为您实际上是使用这一行"updateRecord(jsonData[index])" To solve the issue you can add "index" as a data attribute to the button要解决此问题,您可以将“索引”作为数据属性添加到按钮

"<button data-index=" + index + ">Edit</button>"

then attach a listener to body element after the for loop and check the element is button and has a attribute called index.然后在 for 循环之后将一个侦听器附加到 body 元素并检查该元素是按钮并具有一个名为 index 的属性。 If it is then you can call the update function.如果是,那么您可以调用更新 function。

document.body.onclick = function(event) {
   var index = event.target.getAttribute("index");
   if (index){
     updateRecord(jsonData[index]);
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM