【问题标题】:getting <td> id with jquery not working使用 jquery 获取 <td> id 不起作用
【发布时间】:2018-08-02 17:16:10
【问题描述】:

我是 javascript 新手,我是 jquery,我正在尝试获取元素的 id 和元素的值。

所以这是第一个ajax请求:

   $.ajax({
    type: "POST",
    url: "Home/AddText",
    data: JSON.stringify({ text: newText }),
    contentType: "application/json",
    success: function (result) {
        idRow = result.id;
        $("#myTable").append("<tr id = row" + idRow + "><td id = text>" +
            result.text + "</td><td>" +

            "<input type=checkbox id=checkbox onclick=CrossOut(" + idRow + ")>" + " " +

            "<a class=btnEdit onclick=Edit(" + idRow + ")>Edit</a>" +  " " +

                //show this buttons only if the edit button is clicked
                "<a class=btnSave onclick=Save(" + idRow + ")>Save</a>" + " " +

                "<a class=btnCancel onclick=Cancel(" + idRow + ")>Cancel</a>" + " " +

            "<a class=btnDelete onclick=Delete(" + idRow + ")>Delete</a>"

            + "</td> </tr>");

        idRow++;

        $(document).find('#text').attr('contenteditable', 'true');
        $(document).find('.btnSave').hide();
        $(document).find('.btnCancel').hide();
    }
})

这是函数:

function Save(idRow) {

var newText = $("#text").val();
console.log(newText);

$.ajax({
    type: "POST",
    url: "Home/Update",
    data: JSON.stringify({ id: idRow, text: newText }),
    contentType: "application/json",
    success: function (result) {
        $("#text").add(newText);

        $(document).find('.btnSave').hide();
        $(document).find('.btnCancel').hide();
        $(document).find('.btnEdit').show();
    }
})

}

因此,当我记录 newText 变量时,它不会显示任何内容。

【问题讨论】:

  • 为什么不在 中使用引号?
  • 因为我之前有这个函数 var tbl_row = $(document).find('#row' + idRow); tbl_row.find('#text').attr('contenteditable', 'true'); tbl_row.find('.btnSave').show(); tbl_row.find('.btnCancel').show(); tbl_row.find('.btnEdit').hide();并且它可以在没有引号的情况下工作
  • Id 在文档中必须是唯一的。您有许多 id = text 的输入。
  • 你为什么不使用 JSX 模板或类似的东西,这样你就可以将模板附加到你的表中,并在将要填充的项目上替换 {{ }}?此外,您在进行文档级别查找以进行隐藏和显示时,您可能需要对其进行调整。获取特定元素的位置。
  • 谢谢大家,我把id改成了text1,就成功了。 :D

标签: javascript c# jquery model-view-controller


【解决方案1】:

由于您使用的是td,因此您需要使用.text()

var newText = $("#text").text();

还请注意,如果您继续添加行,您可能拥有多个唯一的 id,而 $(#text) 只会为您提供第一个。

【讨论】:

  • 谢谢,我会尽量保留。
猜你喜欢
相关资源
最近更新 更多
热门标签