本気でやるならonclick属性は避けてライブラリを活用すべき - 帰ってきたHolyGrailとHoryGrailの区別がつかない日記 ã«é¢ãã¦
ãã®å ã HTML ã« onclick ã¨æ¸ãã¦ãç³ãæããããªãããã«æ¸ãã¦ããï¼ï¼
åã onclick å±æ§ããã¡ã ã¨æã£ã¦ããæ代ãããã¾ãããã§ããä»ã¯æã
使ããªãã
ï¼ããã§ãã HTML 㨠JS ã§åæ¥ãã¦ããå ´åã¯ã使ããªãã»ãããããã^^ï¼ããã ãã¯è¨ã£ã¦ãããï¼
JavaScript å
¥éã®è¨äºãæ¸ãã¨ãã« onclick å±æ§ããã¡ã ã¨ããããããããæ¬è³ªçã§ãªããã¨ã説æããªãããããªãã
ç¾ç¶ã§ã¯ onclick å±æ§ãããã£ã¨ãç°¡åã« HTML ã«ã¤ãã³ãããããã³ã°ã§ããæ¹æ³ã ããããããªã«ç®ããããã¦ãªãã¦ãããããããªãããªãï¼
ãã¨ãã°
以ä¸ã¯ãã¯ãªãã¯æã« href ã« GET ãéãããã® onclick å±æ§ã
<a id="hoge" href="/hoge" onclick=" var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP'); req.open('GET', href); req.send(null); return false; ">click</a>
ããã onclick å±æ§ãªãã§ãç¥çµè³ªã«ãããã¨ä»¥ä¸ã®ããã«ãªã
<script type="text/javascript"> // ã¤ãã³ããã³ãã©ã追å function attach(elm, eventType, handler) { if (elm.addEventListener) { elm.addEventListener(eventType, handler, false); } else { elm.attachEvent('on' + eventType, handler); } } // ã¤ãã³ããã³ãã©ãåé¤ function detach(elm, eventType, handler) { if (elm.removeEventListener) { elm.removeEventListener(eventType, handler, false); } else { elm.detachEvent('on' + eventType, handler); } } var elm = document.getElementById('hoge'); var handler = function(event) { /* æ¬è³ªçãªé¨åã¯ãã®ä¸è¡ã ã */ var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"); req.open('GET', elm.href); req.send(null); event = event || window.event; // ã¤ãã³ãã«ãã default åä½ï¼ãã¼ã¸é·ç§»ãªã©ï¼ãç¡å¹åãã if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } // å¿ è¦ã§ããã°ãã¤ãã³ãæµ®ä¸ãæ¢ãã if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true } }; // ã¤ãã³ããå²ãå½ã¦ã attach(elm, 'click', handler); // å¤ããã©ã¦ã¶ã 㨠unload æã« detach ããªãã¨ã¡ã¢ãªãªã¼ã¯ãã attach(elm, 'unload', function() { detach(elm, 'click', handler); detach(elm, 'unload', arguments.callee); }); </script> ï¼ç¥ï¼ <a id="hoge" href="/hoge">click</a>
ãã¡ãããããã¯ãããããªä¾ã ãã©ã onclick å±æ§ã使ããªããã¨ã«ãã£ã¦æ¬è³ªçã§ã¯ãªããã¨ãããããæ¸ããªãã¨ãããªã
ã¨ãã訳ã§
JavaScript ã®å ¥éè¨äºãªã onclick å±æ§ã¯ããã ã¨æãã
ä½è« 1ï¼ã¤ãã³ãå²å½ã¦ä»¥å¤ã§ããã©ã¦ã¶ã®éäºæã£ã¦ããã¾ããªã
å®ã¯ãåºæ¬ç㪠DOM ã«é¢ãã¦è¨ãã°ãã¤ãã³ãã®å²å½ã¦ä»¥å¤ã®éäºæã£ã¦ãã¾ããªãã¨æãã
è¨ãæ¹ãå¤ããã¨ã IE ã® JS ã§ç¹ã«å®è£
ãã ãã£ã¯ãã£ãªã®ã¯ã¤ãã³ãå¨ãã£ã¦ãã¨ã
ã ããã onclick å±æ§ãã使ããã°ãçµæ§ã¹ã ã¼ãºã«å
¥éè¨äºãæ¸ããããããªãããã
ä½è« 2ï¼ã©ã¤ãã©ãªã«é¢ãã¦
ã©ã¤ãã©ãªã¯æµè¡ãå»ããæ¿ãããããç¹å®ã®ã©ã¤ãã©ãªã«ä¾åããããã¾ããªããã°ããè¦ãã¦ããã®ã¯ã©ããã¨æããªã
ãã£ã±ãã DOM ãç´æ¥æ¸ããã»ãããç¥èã¨ãã¦ã¯å¹
åºã使ããã¨æãã¾ããã