最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Hide div when click on a link inside it - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked May 7, 2012 at 14:47 Boos93Boos93 1054 silver badges12 bronze badges 5
  • 3 You shouldn't give duplicate id's to elements, change it to a class if there are duplicates – Mathew Thompson Commented May 7, 2012 at 14:48
  • You sure need to change your code. You have duplicate id's there! Replace them with classes ! – gabitzish Commented May 7, 2012 at 14:49
  • @mattytommo yes, is an option. I know that every id should be unique, I have onlyasked for a possible solution using this code. – Boos93 Commented May 7, 2012 at 15:03
  • @Boos93 So you cannot correct the invalid use of id attributes? Our answer needs to work with invalid code? – Sampson Commented May 7, 2012 at 15:42
  • I could, but I have already found a solution thanks Lokase's answer – Boos93 Commented May 7, 2012 at 15:54
Add a ment  | 

5 Answers 5

Reset to default 5

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 remend 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/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 es to what you are attempting.

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 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./azilif/8/edit#javascript,html

发布评论

评论列表(0)

  1. 暂无评论