javascript - 按下 Enter 后将焦点设置在动态创建的输入字段上

标签 javascript php jquery ajax

我刚刚学习 PHP,现在我正在尝试将它与 ajax 和 javascript 结合起来。

现在我有一个表,它是通过 PHP 从 mysql 数据库中提取的数据动态填充的。除了从数据库中提取的数据之外,还可以在三个附加列中输入结果(对于每个玩家行,该列中都有一个输入字段)。我想要做的是在输入点击时发布数据并将焦点移至其下方的输入字段(而不是旁边)。

这是 PHP 部分:

echo "<table class='table table-hover table-bordered'>"; 
echo "<thead><th class='col-md-1'>Class</th><th class='col-md-1'>Number</th><th class='col-md-3'>Name</th><th class='col-md-1'>Age</th><th class='col-md-1'>Club</th><th class='col-md-1'>m1</th><th class='col-md-1'>m2</th><th class='col-md-1'>m3</th><th class='col-md-1'>Best</th></thead><tbody>";
while ($player = mysql_fetch_assoc($getGroupPlayers)){
    //Loop over players in group! 
    $ageCountry = makeAgeCountry($player['age'],$player['country']);
    echo "<tr><td>".$player['class']."</td><td>".$player['number']."</td><td>".$player['name']."</td><td>".$ageCountry."</td><td>".$player['club']."</td>
    <td class='res1'>
        <input type='name' class='form-control inputfield' id='".$player['p_id']."-res1"."' name='".$player['p_id']."-res1"."'>
    </td>
    <td class='res2'>
        <input type='name' class='form-control inputfield' id='".$player['p_id']."-res2"."' name='".$player['p_id']."-res2"."'>
    </td>
    <td class='res3'>
        <input type='name' class='form-control inputfield' id='".$player['p_id']."-res3"."' name='".$player['p_id']."-res3"."'>
    </td>
    <td>
        <div id='".$player['p_id']."-best"."'></div>
    </td></tr>";
    $counter += 1;
}
echo "</tbody></table>";

Followed this to make the javascript part.

$(document).ready(function() {
    function sendData(elementId) {
       $.ajax({
            url: "handlelivetournament.php",
            type: "post",
            data: "msg="+$('#'+elementId).val(),
            success: function(){   
                alert($('#'+elementId).val());
            },


            error:function(){
                alert("failure");

            }
        });


    }

    $('.inputfield').keypress(function(e) {
    if(e.keyCode == 13) {
        sendData(this.id);
        switch_focus_to_row_below();
    }});
});

现在我想将焦点切换到同一列但下一行的输入字段。问题是我不知道元素的 id。这样的事情可能吗?如果是,一旦它位于该列的最后一行,它是否可以切换到下一列的第一个输入字段?

最佳答案

如果由于某种原因无法使用自定义 ID,您可以使用类。为每个输入添加一个唯一的类。例如,“r1c1”表示第 1 行第 1 列,依此类推。 然后你就可以

  1. 获取聚焦输入字段的当前唯一类。
  2. 在行部分添加 1,
  3. 获取新输入并将焦点设置到它。

关于javascript - 按下 Enter 后将焦点设置在动态创建的输入字段上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41532516/

相关文章:

javascript - 在 Jquery load() 之后设置 div 的高度

javascript - HTML5 Canvas 描边具有一致的 alpha 值

javascript - 2 页面上的 jQuery.contextMenu 具有不同的触发器

javascript - 如何在完成多个异步调用后推迟 Backbone 中的调用?

javascript - 如何在javascript函数中包含php文件?

javascript - 使用数组中的图像填充多个 div,且不重复

php - Vimeo 视频链接正则表达式

javascript - 子类中的 "ReferenceError: this is not defined"

php - 在 jQuery 多文件 uploader 中完成上传后刷新页面

php - new Class() 和 ReflectionClass::newInstance() 的区别?