我正在尝试更新位于 div (div1) 中的聊天内容,但仅当 div1 的内容发生更改时(消息已提交到数据库并在 div1 中拾取)。
我尝试了 here 中的解决方案但我的get无法比较数据。
该解决方案工作完美,但没有内容比较:
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",2000);
}
function startTime()
{
jQuery('#div1').load('index.php #div1 > *');
}
这是在this的基础上修改的,失败了:
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",2000);
}
function startTime()
{
var $main = $('#div1');
$.get('chat.php #div1', function (data)
{
if ($main.html() !== data) $main.html(data);
});
}
我尝试了对这段代码的各种修改,但没有成功...... 我无法重新加载整个页面,如果没有必要,我也不想这样做,因为如果您必须滚动消息,聊天内容会变得更难阅读。 如何解决这个问题?
更新
根据@T.J的建议,我修改了现在可以完美运行的代码:
window.onload = startInterval;
function startInterval()
{
setInterval(startTime,3000);
scrolDown();
}
function startTime()
{
var $main = $('#div1');
$.get('#div1', function (data)
{
elements = $(data);
thisHTML = elements.find("#div1").html();
if ($main.html() !== thisHTML) {
$main.html(thisHTML);
scrolDown();
}
});
}
另一个问题是获取所需的库:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
这显然不是我之前使用的负载所需要的。
最佳答案
您想要使用 get
,但您想要 load
的片段功能,因此您必须自己完成这项工作。然后记住上次得到的内容,只有在不相同时才更新:
var lastHTML;
function startTime()
{
var $main = $('#div1');
$.get('chat.php', function (data) // <== Or index.php, the question has both
{
var elements, html;
// Turn the HTML into elements
elements = $(data);
// Get the HTML of *only* the contents of #div1
html = elements.find("#div1").html();
// If that has changed, use it
if (lastHTML !== thisHTML) {
lastHTML = thisHTML;
$main.html(thisHTML);
}
});
}
请注意,这是片段功能的相当基本的实现(例如,它不会像 load
那样删除脚本)。您可能想看看 load
如何完成其片段内容并复制它(开源的乐趣)。
关于javascript - jQuery,必要时更新内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16792440/