最初に対処する必要があるのは、重複するid
値です。これらを複製しないでください。代わりにclass
、値「box」を格納するために使用します。
<div class="box"><!-- ... --></div>
<div class="box"><!-- ... --></div>
さらに、<a href="delete">
おそらく<a class="delete">
. 以下は、これらの変更を行っていることを前提としています。
次に、「delete」クラス名を持つすべてのリンクへの参照を収集し、親 div を削除または非表示にするハンドラーをそれらにバインドする必要があります。
// Get collection of all anchors
var anchors = document.getElementsByTagName("a");
// Iterate over the collection
for ( var i = 0; i < anchors.length; i++ ) {
// Create an 'alias' for the current anchor being considered
var currentA = anchors[i];
// Is this one of our '.delete' anchors?
if ( currentA.className == "delete" ) {
// Does this browser support addEventListener?
if ( currentA.addEventListener ) {
// Add an event handler via addEventListener
currentA.addEventListener("click", deleteParent, false);
// Or, does this browser use attachEvent?
} else if ( currentA.attachEvent ) {
// Add an event handler using attachEvent
currentA.attachEvent("onclick", deleteParent);
}
}
}
私たちが行ったことは、すべてのアンカーを巡回し、それらのクラス名として「削除」があるかどうかをテストします。対応している場合は、ブラウザーがその方法をサポートしているかどうかを確認するために、少し機能を検出addEventListener
します。存在する場合は、この要素deleteParent
のメソッドにアタッチします。click
メソッドが利用できない場合はaddEventListener
、フォールバックして利用できるかどうかを確認しattachEvent
ます。
これでdeleteParent
、リンクがクリックされるたびに呼び出される関数を作成する必要があります。
この関数は、それを呼び出したリンクへの参照を取得する必要があり、クラス「ボックス」を持つリンクが見つかるまで親の親をクロールします。それが見つかると、それを非表示にします。
// This function handles the "click" event of our '.delete' anchors
function deleteParent(event) {
// Determine which element invoked this function
var link = event.target || window.event.srcElement;
/* In modern browsers, the event object is passed directly into
the handler. This is why we can say event.target and learn
which element invoked the click. In some older browsers
the event object isn't passed into the handler, but instead
is only accessible through the global window object.
This code looks in both places just to be safe. */
// Get initial guess to who '.box' is
var parent = link.parentNode;
// Move up the parent list until we find '.box'
while ( parent.className != "box" )
parent = parent.parentNode;
// Now that we've found '.box', hide it
parent.style.display = "none";
// Prevent anchor form navigating away from page
if ( event && event.preventDefault ) {
event.preventDefault();
} else {
window.event.returnValue = false;
}
/* Similar to the first line of code within this function,
This portion checks to see if an event object exists
(meaning a modern browser is being used) and if that
event has the preventDefault method. If it does, we
invoke that method. On the other hand, if that event
object didn't exist, we assume it must exist on the
window object, and that it must have a property of
returnValue, which we then set to "false". */
}
オンラインの例を使用して、このソリューションをさらに詳しく調べることができます: http://jsbin.com/azilif/8/edit#javascript,html