简体   繁体   中英

Just refreshing certain iframes without refreshing entire page with jQuery

When a page initially loads I have a hidden iframe and other visible ones. Then when a button is clicked I need to hide one that was previously visible, then unhide another (actually I need to set the src attribute too on the one that is becoming visible, but I'll tackle that next). I don't want to refresh the entire page (hence the return false below).

The code below does not display the red iframe2 upon the button click. Can you tell me why?

<form>
  <h1>Test</h1>
  <input type="submit" id="search" value="Search" />
</form>
<iframe id="frame0" style="background-color: blue" height="200" width="800" ></iframe>
<iframe id="frame1" style="background-color: yellow" height="200" width="800" ></iframe>
<iframe id="frame2" style="visibility: hidden; background-color: red" height="200" width="800" ></iframe>

<script type="text/javascript">
$(document).ready(function(){
    $( "#search" ).click(function(event) {
        $("#frame1").hide();
        $("#frame2").show();
        $('#frame2')[0].contentWindow.location.reload(true);
        return false;
    });
});
</script>

User disply insted of visibility edit, your frame2 as below :

<iframe id="frame2" style="display: hidden; background-color: red" height="200" width="800" ></iframe>

Here is working jsfiddle :

https://jsfiddle.net/keval/vqyczm7a

jQuery's .show() and .hide() work with the CSS display property, as oppose to the visibility property.

.show() = css('display', 'block')
.hide() = css('display', 'none')

However, you can use .toggle() to either hide or show an element based on it's current state. I think this is what you would require, as you'd like to hide the one that was previously visible.

You'd need to change your iframe visibility style to use display instead

<iframe id="frame2" style="display: none; background-color: red" height="200" width="800" ></iframe>

Then instead of showing and hiding the iframes, use .toggle()

$( "#search" ).click(function(event) {
    $("#frame1").toggle();
    $("#frame2").toggle();
    $('#frame2')[0].contentWindow.location.reload(true);
    return false;
});

See my working example: https://jsfiddle.net/o2gxgz9r/14250/

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