[英]How to get id from inside div using jquery
How to get the id from the inside div. 如何从内部div获取id。 I have many div with class control but I want to get parent div id.
我有很多div与类控件但我想得到父div id。 How to get?
如何获得?
http://jsfiddle.net/cngt2ef6/7/ http://jsfiddle.net/cngt2ef6/7/
$(".getid").click(function() { alert($(this).closest('div').hasClass("control).attr("id")) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="control" id="spa"> Content </div> <div class="control" id="test"> <div class="method"> <a href="#" class="getid">Getid</a> </div> </div> <div class="control" id="awesome"> Content </div>
The problem comes from : 问题来自:
closest
selector that will return the first parent div
(what is not what we need here). closest
第一个父div
选择器(这不是我们需要的)。 hasClass()
since it will return a boolean if the element has the given class or not. hasClass()
因为如果元素具有给定的类,它将返回一个布尔值。 (in your case the first parent doesn't have the given class control
) control
) Instead of using hasClass()
you need to use the class
selector directely in the closest()
method like: 您需要在nearest
closest()
方法中直接使用class
选择器,而不是使用hasClass()
,如:
$(this).closest('div.control').attr("id");
$(".getid").click(function() { console.log($(this).closest('div.control').attr("id")); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="control" id="spa"> Content </div> <div class="control" id="test"> <div class="method"> <a href="#" class="getid">Getid</a> </div> </div> <div class="control" id="awesome"> Content </div> Js:
Besides closest()
- which return the first single node parent - already mentioned you can use parents()
, but in this case will return multiple nodes with the element/class/id targeted. 除了
closest()
- 返回第一个单节点父节点 - 已经提到过你可以使用parents()
,但在这种情况下将返回多个节点,其中元素/ class / id是目标。
It is just an alternative to closest()
in this case scenario 在这种情况下,它只是
closest()
的替代方案
$(".getid").click(function() { console.log($(this).parents('.control').attr("id")) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="control" id="spa"> Content </div> <div class="control" id="test"> <div class="method"> <a href="#" class="getid">Getid</a> </div> </div> <div class="control" id="awesome"> Content </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.