首页 > 解决方案 > JS 统计其他页面中具有相同类的元素个数

问题描述

我正在尝试找到一种解决方案,将一些元素与我的其他页面上的特定类一起放置。是否可以仅通过我们使用 JS 将这些数据从一个页面传递到另一个页面?我可以在第二页不植入任何代码的情况下解决它吗?

第 1 页(将包括 div)

<div class"toy"></div>
<div class"toy"></div>
<div class"toy"></div>
<div class"toy"></div>
<div class"toy"></div>

第 2 页(这里的数字应该是从第 1 页计算具有“玩具”类的 div 的结果)。

5 个玩具等着你。

标签: javascripthtmlcss

解决方案


假设http://example.com/page1.html是您示例中第一页的地址。这是一个 JS 代码,它通过加载第 1 页并解析它来计算元素的数量:

function onCount(count) {
    if (typeof count === 'number') {
        alert('There are ' + count + ' Toys waiting for you');
    } else {
        alert('An error has happened');
    }
}

function ajaxGet(url, onload, onerror) {
    var request = new XMLHttpRequest();
    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            onload(request.responseText);
        } else {
            onerror();
        }
    };
    request.onerror = onerror;
    request.open('GET', url, true);
    request.send();
}

ajaxGet('http://example.com/page1.html', function (response) {
    var dom = new DOMParser().parseFromString(response, 'text/html');
    onCount(dom.querySelectorAll('.toy').length); // '.toy' is a CSS selector of an element you need to count
}, function () {
    onCount(false);
});

您应该将此代码添加到第二页的 JavaScript 代码中。


推荐阅读