<div id="pic">
<div id="left">
<img src="images/left.png" />
</div>
<div id="right">
<img src="images/right.png" />
</div>
</div>
I want to hide the div
with id
"right" when I click on the div
with id
"left"
Code I am using:
$("#left").click(function(){$("#right").hide();});
This is not working, 开发者_高级运维what is the reason? And how will I achieve what I intend to?
There are one of three things wrong, since your code is technically correct:
- Your click function does not appear in your
$(document).ready
function - Your page repeats ids. Use classes instead.
- Your divs are created dynamically and therefore not bound on
$(document).ready
(1) is a simple fix. Just put in your $(document).ready
. (2) just change your id
attributes to classes, but if you want to make sure that you hide the correct div you may need to do some traversing. (3) can be fixed by using $(selector).bind('click', function(){});
or $(selector).live('click', function(){});
Good luck
UPDATE (1/24/12) - If you're using jQuery 1.7+, you should use $(selector).on('click', function(){});
, not bind()
or live()
Your code is correct and works for me.
Something else is wrong.
Try setting up the handler in document.ready
$(document).ready(function() {
$("#left").click(function() { $("#right").hide(); });
});
The click event can only be added after the #left div has loaded. For this reason wrap your existing jquery in a domready call.
$(document).ready(function(){
$("#left").click(function(){$("#right").hide();});
});
Your code seems to be fine, but looks like you are missing the jQuery's ready
event, try this:
$(function(){
$("#left").click(function(){
$("#right").hide();
});
});
Note: $(function(){
is short form of ready
event code.
Some possibilities:
- did include the jquery.js file in the html head
- are there no bugs in the preceding javascript before that jquery line? They could stop execution before reaching that point.
- are the id's unique? Maybe you have multiple elements with id='right'?
精彩评论