满足于表:选择单元格

时间:2015-07-19 14:34:36

标签: php jquery mysql function select

我在php中生成一个表。每个单元格都有一个不同的id,它由列名和行号组成。

<tr>
    <td contenteditable="true" id="i-date-1">26/03/2014</td><td id="i-amount-1">200</td>
    <td contenteditable="true" id="i-date-2">26/04/2014</td><td id="i-amount-2">300</td>
</tr>

我想通过jQuery记录sql数据库中的更改。为此,我需要为每个单元格添加一个eventListener,然后调用一个将数据发布到服务器端php脚本的函数,但我对如何做到这一点感到困惑,这是我的尝试#39; t work:

$(['id*="i-"']).each(function() {
            $(this).addEventListener("blur", updateFunction, false);
            $(this).spellcheck = 'true';
});

然后是我的更新功能:

function updateFunction()
{
    var lineID = $(this).attr(id);
    var needle = lineID.indexOf("-");
    needle = lineID.indexOf("-", needle);
    needle = needle + 1 ;
    lineID = lineID.substr(needle);
    $.ajax({
        type: "get",
        url: "queries.php?q=update&iID="+lineID,
    });
}

1)我是否正确向所有单元格添加eventListener或者更容易? 2)我的updateFunction很糟糕,我知道:)但我没有足够的经验来弄清楚如何解决它...如果有人可以提供帮助?

提前感谢您的时间。

2 个答案:

答案 0 :(得分:1)

通过一些更改,它可以很好地工作,就像这样。

$("[id*='i-']").on("blur", updateFunction).prop('spellcheck', true);
function updateFunction()
{
  var lineID = $(this).attr('id');
  var needle = lineID.indexOf("-");
  needle = lineID.indexOf("-", needle);
  needle = needle + 1 ;
  lineID = lineID.substr(needle);
  $.ajax({
    type: "get",
    url: "queries.php?q=update&iID="+lineID,
  });
}

这是一个演示 http://jsbin.com/nitewe/edit?js,output

使用data-*属性来存储其他信息,例如data-1date-2

,而不是分割ID
<td contenteditable="true" class="i-date" data-date="date-1">26/03/2014</td><td class="i-amount">200</td>
<td contenteditable="true" class="i-date" data-date="date-2">26/04/2014</td><td class="i-amount">300</td>

使用这样的结构只需要脚本就可以了。

$(".i-date").on("blur", updateFunction).prop('spellcheck', true);
function updateFunction()
{
  var lineID = $(this).data('date');
  var amt = $(this).next('.i-amount');
  $.ajax({
    type: "get",
    url: "queries.php?q=update&iID="+lineID,
  });
}

.next([selector])将使用类.i-amount获取对下一个兄弟的引用。

演示 http://jsbin.com/sucozu/edit?html,js,output

答案 1 :(得分:1)

将id的值保留为

的属性
<td contenteditable="true"  dateId="date-1">26/03/2014</td><td id="i-amount-1">200</td>
<td contenteditable="true"  dateId="date-2">26/04/2014</td><td id="i-amount-2">300</td>

function updateFunction()
{
    lineID = $(this).attr('dateId');
    $.ajax({
        type: "get",
        url: "queries.php?q=update&iID="+lineID,
    });
}
相关问题