javascript - 用 Ajax 响应替换 div 的内部 HTML

标签 javascript jquery html ajax

我正在尝试在一段时间后更改 div 的内部 HTML。 我得到了 Ajax 想要的正确响应。 但无法用 Ajax 响应替换选定的内部 HTML。 我的代码有什么问题..

HTML

      <p class="time ui-li-desc" data-time="2013-02-13 11:30:08" >
    51 seconds ago<img alt="image" src="images/read.png"></p>

      <p class="time ui-li-desc" data-time="2013-02-13 11:30:16" >
    58 seconds ago<img alt="image" src="images/read.png"></p>
.
.
.
.
.
      <p class="time ui-li-desc" data-time="2013-02-13 11:40:08" >
    10 minute ago<img alt="image" src="images/read.png"></p>

j查询

setInterval(function() { 
            $( ".time" ).each(function( index ) {
                var sendTime=  $(this).attr("data-time");
                dataString = "sendtime="+sendTime+"&q=convertTime";
                $.ajax({
                    type: "POST",
                    url: "data_handler.php",
                    data: dataString,                   
                    cache: true,
                    success: function(response) {
                        alert(response);
                        $(this).html(response);
                        //alert(response);
                    }
                });
            });
        }, 5000);

最佳答案

this 是回调中的窗口。使用赋予每个 :

callback 的值
        $( ".time" ).each(function(index , elem) {
            var sendTime=  $(this).attr("data-time");
            dataString = "sendtime="+sendTime+"&q=convertTime";
            $.ajax({
                type: "POST",
                url: "data_handler.php",
                data: dataString,                   
                cache: true,
                success: function(response) {
                    alert(response);
                    $(elem).html(response);
                }
            });
        });

不需要定义一个新变量来保护this,因为jQuery 已经为您做了。

关于javascript - 用 Ajax 响应替换 div 的内部 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14851684/

相关文章:

javascript - 避免 DOM 元素在 .text() 上被删除的方法

html - 固定高度 div 之上的可变高度 div

javascript - JavaScript 可以用来加载另一个页面的元数据内容吗?

jquery - 如何在我的 jquery 中的 <p> 标记中添加新行?

javascript - 右键单击是 Javascript 事件吗?

javascript - Jquery 和 css 单击打开菜单并显示事件菜单

php - 按 ID 更改选定的下拉列表

html - 使所有列宽等于最宽列的长度

php - 在网页执行之前创建强制选择弹出窗口

javascript - 一种测试javascript方法的方法