▽1
●
a-kuma3 ●200ポイント ベストアンサー |
リンクをクリックされたときのイベントで、いわゆる Ajax で使われる XMLHttpRequest を使うか、JSONP で使われる script タグの埋め込みを使うことになると思います。
きっとクリック数をカウントしたいページはたくさんあると思うので、
というようなことを意識してみました。
どちらもクリックのイベントハンドラを A タグにぶら下げて、イベントハンドラで href 属性から id を切り出すところまでは同じです。
XMLHttpRequest を使う場合は、こんな感じ。
<script> (function() { var countUp = function(a) { var match = /.*\/([^/]+)\.html/.exec(a.href); if (match) { var url = "count.php?id=" + match[1] + "&hoge=hoge"; var xhr = new XMLHttpRequest(); xhr.onload = function() { // NOP }; xhr.open("GET", url); xhr.send(); xhr = null; } }; window.addEventListener("load", function() { Array.prototype.forEach.call(document.getElementsByTagName("a"), function(a) { a.addEventListener("click", function(ev) { countUp(ev.target); }); }); }); })(); </script> ... <a href="aaaaa.html">aaaaa</a> <a href="bbbbb.html">bbbbb</a>
script タグの追加を使う場合は、こんな感じ。
<script> (function() { var countUp = function(a) { var match = /.*\/([^/]+)\.html/.exec(a.href); if (match) { var url = "count.php?id=" + match[1] + "&hoge=hoge"; var e_script = document.createElement("script"); e_script.src = url; document.body.appendChild(e_script); } }; window.addEventListener("load", function() { Array.prototype.forEach.call(document.getElementsByTagName("a"), function(a) { a.addEventListener("click", function(ev) { countUp(ev.target); }); }); }); })(); </script> ... <a href="aaaaa.html">aaaaa</a> <a href="bbbbb.html">bbbbb</a>