How to use regex for jquery selector to apply some attribute to elements?

问题: I have an edit button which should make the contents of that table editable. The button id and class looks like this. id="edit_icon_'.$row1["client_id"].'_'.$row2["projec...

问题:

I have an edit button which should make the contents of that table editable. The button id and class looks like this.

id="edit_icon_'.$row1["client_id"].'_'.$row2["project_id"].'"
class="editbtn"

Id depends on db values. Onclick of this button, I want all the elements of a table "just one table" to be editable..

<tr>
    <td id="edit_elem_'.$row2["project_id"].'_'.$row3["detail_id"].'">'.$row3["elements"].'</td>
    <td id="edit_respon_'.$row2["project_id"].'_'.$row3["detail_id"].'">'.$row3["responsibilty"].'</td>
    <td id="edit_remark_'.$row2["project_id"].'_'.$row3["detail_id"].'">'.$row3["remarks"].'</td>
</tr>

This is what table rows look like.. All have dynamic ids. How should i write the selectors with regex for this to work?

$(document).on('click', '.editclick', function() { //entering edit mode
    var str = $(this).attr("id");              // edit_icon_1_124
    var cid = str.replace(/^D+|D.*$/g, "");  // 1
    var pid = num = str.replace(/.*D/g, "");  // 124
    $('').each(function(){                 //  #edit_*_pid_* -expected, *-wildcard
        $(this).attr('contenteditable','true'); 
    });
});

Edit: P.S. I have multiple tables generated on the same page..


回答1:

You don't need REGEX for that. You can use data- attribute to store the id that the edit button is intended to edit.

The button:

<button class='editclick' data-pid="124" data-did="1">Edit</td>

The Table (add class for every did and pid):

<tr>
    <td id="edit_elem_'.$row2["project_id"].'_'.$row3["detail_id"].'" class="p'.$row2["project_id"].' d'.$row3["detail_id"].'">'.$row3["elements"].'</td>
    <td id="edit_respon_'.$row2["project_id"].'_'.$row3["detail_id"].'" class="p'.$row2["project_id"].' d'.$row3["detail_id"].'">'.$row3["responsibilty"].'</td>
    <td id="edit_remark_'.$row2["project_id"].'_'.$row3["detail_id"].'" class="p'.$row2["project_id"].' d'.$row3["detail_id"].'">'.$row3["remarks"].'</td>
</tr>

The JavaScript:

$(document).on('click', '.editclick', function() { //entering edit mode
    var cid = $(this).data('did');  // 1
    var pid = num = $(this).data('pid')  // 124
    $("td.d"+did+".p"+pid).attr('contenteditable','true');
});
  • 发表于 2019-03-17 14:55
  • 阅读 ( 166 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除