javascript - 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 个玩具等着你。
解决方案
假设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 代码中。
推荐阅读
- python - 在继承的类中获取动态参数值 - django
- api - WSO2 API 管理器不工作 https 端点
- python - 在 python 的 GUI 中显示来自服务器的更新数据
- laravel - 在 Tailwind 中创建一个类似于 bootstrap 的网格系统
- wordpress - 如何在wordpress中为帖子创建自定义属性
- apache-camel - 如何在 Apache Camel 中为 jsonpath 编写存在谓词?
- junit - SONAR 代码覆盖率未反映在私有方法中
- recaptcha-enterprise - Google Enterprise Recaptcha 对未记录请求的基本指标进行评分
- tensorflow - 从 1.x 迁移到 TensorFlow 2.x 会导致 Google AI 平台上的训练和 ResourceExhaustedErrors 慢得多
- postgresql - PostgreSQL如何安全地删除pg_wal目录中的文件