简体   繁体   English

jQuery选择器返回未定义

[英]JQuery selector returns undefined

This html code was generated of my php code, but I copied this out of the HTML code of the browser. 该html代码是由我的php代码生成的,但是我从浏览器的HTML代码中复制了此代码。

The console.log prints out undefined. console.log打印出未定义的内容。 I don't know why. 我不知道为什么 It's probably a really dumb mistake, like always. 像往常一样,这可能是一个非常愚蠢的错误。 Thank you for your help. 谢谢您的帮助。

 $('.show').click(function() { var id = $(this).attr('id'); var div = $("div#" + id); console.log(div.html()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3>Heading <a href='#' class='show' id='2962'>+</a></h3> <div class='.slidetoggle' id='2962' style='display: none;'> <p>Test!</p> </div> 

It's because the .show element is an a , not a div . 这是因为.show元素是a而不是div The selector is wrong: 选择器错误:

var div = $("a#" + id);

Update: 更新:

You are right, but I want to show the div, not the a 您是对的,但我想显示div,而不是a

In this case you need to use DOM traversal to find the relevant element. 在这种情况下,您需要使用DOM遍历来查找相关元素。 Your current code doesn't work as you have duplicate id attributes. 您当前的代码无效,因为您具有重复的id属性。 This is invalid as they must be unique. 这是无效的,因为它们必须是唯一的。 Try this: 尝试这个:

 $('.show').click(function() { $(this).closest('h3').next('.slidetoggle').slideToggle(); }); 
 .slidetoggle { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3>Heading <a href="#" class="show">+</a></h3> <div class="slidetoggle"> <p>Test!</p> </div> <h3>Another Heading <a href="#" class="show">+</a></h3> <div class="slidetoggle"> <p>Another Test!</p> </div> 

我尚无评论的声誉,因此我将不得不作答,但您想要的元素是锚点,但您的jQuery选择器定位的是元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM