简体   繁体   中英

Hide div when click on a link inside it

My code is similar to this:

<div id="box">
    <a href="delete">delete</a>
</div>
<div id="box">
    <a href="delete">delete</a>
</div>
<div id="box">
    <a href="delete">delete</a>
</div>

I want to hide the first div on click on the link inside it, the same for the second and third divs. Is there any way to do it without change this code?

Yes.

You create JavaScript elsewhere on the page which:

  1. Defines an onclick handlder function "deleteMe()"

    • The function will have access to this variable which will point to the <a> element of the DOM that was clicked on.

    • From which you can walk up the DOM to the parent element, to find the correct box div DOM element

    • Then change that box div's style from block to hidden

  2. Then your JS should loop through every element with ID="box" (I don't think you can do it with getElementById() so you may need too loop over the DOM children of containing node). For each of the box DIVs:

    • Find its first child in DOM via firstChild() - that will be the <a> DOM element.

    • Assigns the above onclick handlder function "deleteMe()" to <a> DOM element.


Please note that I would recommend fixing the HTML to have unique IDs. You don't have to have them unique but it is better design wise.

What you use duplicate IDs for should be handled via classes.

I wouldn't use HREF's to initiate the event, I would simply use a DIV. None the less you can use the preventDefault function to stop the HREF from proceeding if you want to keep using HREFS.

Here is a JSFiddle to start you out: http://jsfiddle.net/PbzYz/

I'm assuming your a novice so perhaps you would find JQuery easier to use it basically simplifies JavaScript and makes it easier to code with.

Here is an example of how you would code this in JQuery

<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {

    $("a").click(function() { //Onclick <a></a>
        $(this).parent().hide(); //Hide it's parent
        return false; //stops the link from submiting
    });

});
</script>

You can do this with plain JavaScript but I prefer JQuery especially if your going to do a lot of coding in JS.

I also agree with DVK it's a bad habit to get into when using id's more than once they where designed to be unique, classes would be the best option for you when it comes to what you are attempting.

The very first thing you need to address is the duplicate id values. You shouldn't duplicate these. Instead, use class to store the value "box".

<div class="box"><!-- ... --></div>
<div class="box"><!-- ... --></div>

Additionally, your <a href="delete"> should probably be <a class="delete"> . The following assumes you have made these changes.

Next we need to gather up a reference to all links that have the "delete" class name, and bind to them a handler that will either remove, or hide their parent 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);

    }

  }

}

What we have done is cycled over all anchors, and tested if they have "delete" as their class name. If they do we proceed to do a bit of feature detection to see if the browser supports the addEventListener method. If it does, we attach deleteParent to the click method of this element. If the addEventListener method isn't available, we fallback to check if attachEvent is.

With this, we now need to create the function deleteParent that will be called whenever the links are clicked.

This function needs to get a reference to the link that invoked it, and then crawl up its parent parents until it finds one with the class "box". When it finds that, it hides it:

// 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". */

}

You can study this solution further via the online example: http://jsbin.com/azilif/8/edit#javascript,html

You can use JQuery inside the head of the HTML page.

First of all you will need to make the ID's of the boxes unique or clicking one delete link would delete all of the boxes.

If you make your HTML look like this:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
  $("#delete1").click(function(){
    $("#box1").hide();
  });

  $("#delete2").click(function(){
    $("#box2").hide();
  });

  $("#delete3").click(function(){
    $("#box3").hide();
  });
});
</script>
</head>

<body>
<div id="box1">
       <a id="delete1">delete</a>
    </div>
    <div id="box2">
        <a id="delete2">delete</a>
    </div>
    <div id="box3">
        <a id="delete3">delete</a>
    </div>
</body>
</html>

The Jquery needed is in the of the document. You may need to make sure you upload the latest version of jquery.js to your server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM