javascript - jQuery,必要时更新内容

标签 javascript jquery html get load

我正在尝试更新位于 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/

相关文章:

javascript - 在 Azure 上作为静态应用程序托管的 Create-react-app 未检测到环境变量

javascript - vue 组件(静态)不工作。我想要解决方案

javascript - 在 Javascript 中通过 onclick 事件调用的函数中使用此函数

javascript - 如何在 HTML 中重复 n 次 div 元素?

javascript - 下拉列表未在 asp.net 中获取 CSS

jquery - Webstorm:通过库添加 jQuery 但无法在 html 中添加引用

javascript - 包含多行文本的元素,如何向上溢出?

javascript - jQuery :not() selector does not work in . off() 方法

html - 在一行中定位元素

html - 寻找模板 "Category"