【问题标题】:reload only TR if clicked如果单击,则仅重新加载 TR
【发布时间】:2016-07-11 14:31:55
【问题描述】:

我在 HTML 表 <tr>'s 和 <td>'s 中列出来自 SQL 的项目。该表位于一个 div 中,每30 秒都会使用 jQuery AJAX 刷新(这就是 div 具有唯一 ID 的原因)。这部分工作正常。这是 HTML:

function auto_load()
{
    $.ajax({
        url: "/folder/content.php",
        cache: false,
        success: function(data){
            $("#live").html(data);
        } 
    });
}

$(document).ready(function(){
    auto_load(); //Call auto_load() function when DOM is Ready
});
setInterval(auto_load,30000);
<div id="live">
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
            </tr>
        </thead>
	    <tr>
    	    <td></td>
            <td></td>
        </tr>
        <!-- and so on -->
    </table>
</div>

现在我想做的是让每一个都可以点击,但是如果它被点击, 1) 一个 GET 请求被发送到一个 PHP 文件,指示点击了哪个特定文件; 2) 之后仅刷新特定的(或其中的内容),而不是整个页面。

我无法使用常规的 http 链接来执行此操作,因为如果单击 a,则将重新加载整个页面。

由于这是我知识不足的地方,也许有人可以分享一些关于如何解决这个问题的想法。谢谢!

【问题讨论】:

  • 所以检测一个 TD 的点击,获取 id,进行 ajax 调用,替换 HTML。你有什么问题?
  • 感谢您的快速回复。我稍微编辑了文本,现在指的是 TR-s 而不是 td-s。问题是我对 Javascript 不太了解,因此甚至不知道要寻找什么。也许有人可以给我一些简单的例子。
  • 你可能想从阅读api.jquery.com/jquery.ajax开始

标签: javascript php jquery ajax twitter-bootstrap


【解决方案1】:

不确定您到底想要什么,但如果我知道您想要加载该行?因此,您想监听对行的点击、读取单元格、进行 ajax 调用并替换内容。

$("#live").on("click", "tbody tr", function() {  //listen for click on a table row
    var tr = $(this),  //the row
        tds = tr.find("td"),  //the cells of the row
        id = tds[0].text(),  //the first column text
        output = tds[1]; //where to output

    $.ajax({
        method: "POST",
        url: "some.php",  //where to post the data
        data: { id: id }  //value to pass to the server
    })
    .done(function( result ) {
        output.html(result);   //output the returned value
    })
    .fail(function() {
        alert( "error" );
    });
});

如果这不正确,并且您想要加载整个表格,那么您只需查找树即可获取 div。

$(document).on("click", "tr", function() { 
    var div = $(this).closest("div");
    console.log(div.attr("id"));
    div.load("foo.php?id=" + div.attr("id")); 
});

【讨论】:

    【解决方案2】:

        $('#myTable').on('click', '.someClass',function () {
            var trID=$(this).attr('id');
            $(this).find('td').append(new Date());//replace this with your AJAX call
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table id="myTable">
            <tr id="x" class="someClass"><td>Click Me 1</td></tr>
            <tr id="y" class="someClass"><td>Click Me 2</td></tr>
        <table>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多