Javascript change div content upon a click

2019-02-28 09:43发布

问题:

I'm pulling a content from PHP array and I have a situation like this:

 <div class="weight-display">
 <span>04/25/2011</span> <span>100lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
 </div>
 <div class="weight-display">
 <span>04/27/2011</span> <span>150lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
 </div>
 etc...

Now when somebody clicks on Edit within, let's say, first div where weight is 100lbs, I just need that "div" to change and to have input field instead of simple text where weight is (while others will remain the same) and to be like this:

<div class="weight-display">
<span>04/25/2011</span> <input type="text" value="100" /> <span>Save</span> <span>Cancel</span>
</div>
<div class="weight-display">
<span>04/27/2011</span> <span>150lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
etc..

So basically div has to "reload itself" and change content. Now I really need some very simple Javascript solution. Preferably I would like a solution with a hidden div beneath original one, so they just swap places when user clicks on EDIT and in a case if CANCEL is pressed to swap places again so original div with text is displayed...

Thanks, Peter

回答1:

<style type="text/css">
    /* Normal mode */
    .weight-display div.edit {display:none}
    /* Editor mode */
    .weight-edit div.show {display:none}
</style>
<div class="weight-display">
    <button onclick="toggle(this)">Edit this!</button>
    <div class="edit"><input type="text" value="Test" /></div>
    <div class="show">Test</div>
</div>
<script type="text/javascript">
    function toggle(button)
    {
        // Change the button caption
        button.innerHTML = button.innerHTML=='Edit this!' ? 'Cancel' : 'Edit this!';
        // Change the parent div's CSS class
        var div = button.parentNode;
        div.className = div.className=='weight-display' ? 'weight-edit' : 'weight-display';
    }
</script>


回答2:

What you suggest is basically correct. I would generate two div's one for display and one edit. The edit div will initially have display: none. When the Edit is clicked, hide the display div and show the edit div.



回答3:

How about something like:

onClick event calls a function (EDITED to be a little smarter than my original brute force method):

function swapdivs ( id_of_topdiv, id_of_bottomdiv ) {
  var topdiv    = getRefToDiv( id_of_topdiv );
  var bottomdiv = getRefToDiv( id_of_bottomdiv );

  var temp  = topdiv.style.zIndex;
  topdiv    = bottomdiv.style.zIndex;
  bottomdiv = temp.style.zIndex;
}

Could that or similar work for you? Or am I missing some subtle yet crucial requirement?