Jquery - 单击以编辑脚本

时间:2014-08-13 19:32:56

标签: javascript jquery html

我有一个数据表,用户可以通过点击编辑信息。点击将使用输入文本字段替换数字数据,该字段允许用户提交他们的编辑。我已经包含一个“取消”链接,一旦点击,输入字段将消失,数据文本重新出现。但是,如果我单击编辑多行并取消它,数据文本将重新显示为我单击的第一行。

例如,我的数据表看起来像这样

Ref No.  |  Container No.
0006     |  OLKI2940
0005     |  KL2223KL
0004     |  PPO80596
0003     |  JLJ93459

如果我点击编辑容器#“OLKI2940”,我取消它,“OLKI2940”将重新出现。但是,如果我单击编辑第二行Container#“KL2223KL”并取消,将出现Container#“OLKI2940”。所以它复制了我点击的第一行。如何才能显示正确的容器编号?

我的HTML如下:

// this is in a loop
<tr>
   <td>{{ refnum }}</td>
   <td id="{{ ctrnum }}"><a href="#" class="ctrnoedit">{{ ctrnum }}</a></td>
</tr>

我的JS:

// editing container no
   $('#containers').delegate("a.ctrnoedit","click", function() {
      var index = $(this).closest("td").attr("id");
      var html = "<form id='editctrno' method='post'><input name='ctrnum' type='text' value='"+index+"'>" +
    "<br><button type='submit'>Update</button> <a href='#' id='canceledit'>Cancel</a></form>";
      $(this).closest("td").html(html);

    $('#containers').delegate("a#canceledit", "click", function() {
         $(this).closest("#editctrno").html("<a href='#' class='ctrnoedit'>"+index+"</a>");
    })
})

JS小提琴示例:

http://jsfiddle.net/9Lsgw2ve/1/

1 个答案:

答案 0 :(得分:0)

虽然您的编码方式通过生成重复ID而违反了html规则,但这是 Working Demo

var index='';
// editing container no
$('#containers').delegate("a.ctrnoedit", "click", function () {
    index = $(this).closest("td").attr("id");
    var html = "<form id='editctrno' method='post'><input name='ctrnum' type='text' value='" + index + "'>" +
        "<br><button type='submit'>Update</button> <a href='#' id='canceledit'>Cancel</a></form>";
    $(this).closest("td").html(html);

    $('#containers').delegate("a#canceledit", "click", function () {
        $(this).closest("#editctrno").html("<a href='#' class='ctrnoedit'>" + index + "</a>");
    })
})

您只需要从index函数

中定义click

如果你想获得与链接中完全相同的值,那么试试这个:

<强> DEMO

var index='';
// editing container no
$('#containers').delegate("a.ctrnoedit", "click", function () {
    index = $(this).closest("td").children('a').html();
    var html = "<form id='editctrno' method='post'><input name='ctrnum' type='text' value='" + index + "'>" +
        "<br><button type='submit'>Update</button> <a href='#' id='canceledit'>Cancel</a></form>";
    $(this).closest("td").html(html);

    $('#containers').delegate("a#canceledit", "click", function () {
        $(this).closest("#editctrno").html("<a href='#' class='ctrnoedit'>" + index + "</a>");
    })
})