问题描述:

I'd like to hide and show a div(jQuery toggle()). This is an example of my code:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>

$("a").click(function() {

var myelement = $(this).attr("href");

$(myelement).slideToggle("slow");

$(".toggle:visible").not(myelement).hide(500);

});

</script>

<h2><a href="#box1"> Programming</a></h2>

<div id="box1" class = "block-content" style="display:none">

box 1

</div>

<h2><a href="#box2"> software</a></h2>

<div id="box2" class = "block-content" style="display:none">

box 2

</div>

It doesn't work and Firebug doesn't show me an error message.

Can you help me ?

网友答案:

Demo: http://jsfiddle.net/xyzpq44x/

  • API: preventDefault you want to prevent default behaviour of a tag http://api.jquery.com/event.preventdefault/

rest should help :)

try this

$("a").click(function (e) {
    e.preventDefault();
    var myelement = $(this).attr("href")
    $(myelement).slideToggle("slow");
    $(".toggle:visible").not(myelement).hide(500);

});
网友答案:

When the script runs, the a tags are not yet present on the page!

Put your script below the html elements, or use document ready or equivalent to postpone the script execution.

网友答案:
$(".toggle:visible").not(myelement).hide(500);

replace ".toggle:visible" with "div"

相关阅读:
Top