你需要解决的第一件事情是重复id
值。你不应该复制这些。而是使用class
来存储“框”的值。
<div class="box"><!-- ... --></div>
<div class="box"><!-- ... --></div>
此外,您<a href="delete">
也许应该<a class="delete">
。以下假定您已经做出这些更改。
接下来,我们需要聚集到具有“删除”类名的所有链接参考,并绑定到他们的处理程序,将要么删除,或隐藏他们的父母格。
// 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
,每当链接被点击时,这个函数将被调用。
该函数需要获取对其引用的链接的引用,然后抓取其父代父节点,直到找到具有“box”类的链接。当它发现,它隐藏它:
// 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
你不应该给副本ID对元素,将其更改为一类,如果有重复 – mattytommo
是jQuery的一个选择吗? – mattytommo
您确定需要更改您的代码。你有重复的ID在那里!用类替换它们! – gabitzish