开发者

jQuery, access div inside a div

开发者 https://www.devze.com 2022-12-21 18:08 出处:网络
<div id=\"pic\"> <div id=\"left\"> <img src=\"images/left.png\" /> </div> <div id=\"right\">
<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:

  1. Your click function does not appear in your $(document).ready function
  2. Your page repeats ids. Use classes instead.
  3. 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:

  1. did include the jquery.js file in the html head
  2. are there no bugs in the preceding javascript before that jquery line? They could stop execution before reaching that point.
  3. are the id's unique? Maybe you have multiple elements with id='right'?
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号