【发布时间】:2013-04-11 23:22:48
【问题描述】:
我在 ip 上创建了一个独特的点击/点击计数器。
为了显示clic的数量,我在body标签上使用了onload函数。 例如:
<body class="homepage" onload="affiche_compteur('compteur1'); affiche_compteur('compteur2');affiche_compteur('compteur3');affiche_compteur('compteur4');affiche_compteur('compteur5');affiche_compteur('compteur6');">
affiche_compteur(法语)= display_counter
我需要使用 onload 调用我的 html 页面中存在的每个点击计数器。 (它适用于硬编码元素,但在我的情况下,我已经在文档上附加了我的 html 页面中不存在的元素(未硬编码))
有没有办法获取点击计数器的每个 id 以避免在加载时添加每个计数器?
这是我的 ajax 脚本:
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
xhr = false;
}
return xhr;
};
function affiche_compteur(id_clics)
{
var xhr = getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById(id_clics).innerHTML = xhr.responseText;
}
};
xhr.open('POST', './compteur/affiche_compteur.php', true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send('compteurId='+id_clics);
}
这里是被点击元素的html:
<div class="element blog " id="_13">
<a class="link" href="/portfolio/dock.html" onclick="gestionClic('compteur13');">
</a>
</div>
<div class="element blog " id="_12">
<a class="link" href="/portfolio/dock.html" onclick="gestionClic('compteur12');">
</a>
</div>
<div class="element blog " id="_11">
<a class="link" href="/portfolio/dock.html" onclick="gestionClic('compteur11');">
</a>
</div>
对不起我的英语,我是法国人。
【问题讨论】:
-
只是出于好奇:如果您使用 jQuery,为什么要推出自己的 XHR,而不使用 jQuery
ajax()实现? -
我不知道...我这样写是为了能够读取 php 脚本。如果 ip 不存在,则在数据库中写入递增的点击数...