Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 获取$的id(此)_Jquery - Fatal编程技术网

Jquery 获取$的id(此)

Jquery 获取$的id(此),jquery,Jquery,我尝试获取在内容中搜索的元素的id: $headings = jQuery('.kb-content').find('h2'); jQuery($headings).each(function() { jQuery('#kb-postnav .nav').append('<li><a href="'+$(this).attr('id')+'">'+$(this).text()+'</a></li>'); }); 编辑:很抱歉我的错误,发现

我尝试获取在内容中搜索的元素的id:

$headings = jQuery('.kb-content').find('h2');
jQuery($headings).each(function() {
    jQuery('#kb-postnav .nav').append('<li><a href="'+$(this).attr('id')+'">'+$(this).text()+'</a></li>');
});
编辑:很抱歉我的错误,发现了问题:h2元素的id是在我的函数之后创建的。但是这个函数也为h2元素添加了额外的内容。所以我现在想得到父母的id。 像


这是一个测试

因此,我想在find('h2')之后获取父元素,此时元素已经在find列表中。

您找到的元素没有id,因为
此.id
工作正常:

jQuery('.kb content h2').parent().each(function(){
警报(this.id);
});
/*另类
jQuery('.kb content h2').each(function(){
警报(this.parentElement.id);
});
*/

标题

你可以这样做。id那么你找到的元素没有id。我同意@RobertMcKee。您试图查找的元素似乎不包含任何id。请重新检查。此操作有效。有什么问题吗?可能您的
h2
元素没有ID。发布您的HTML,这可能会有所帮助。:)发现问题:元素id是由另一个函数在我的函数之后分配的。有没有办法获取父元素的id?
this.parentElement.id
$(this.parent().attr(“id”)
$(this.parent()[0]。id
工作正常:)谢谢!@tymeJV的答案也应该有效。His使用jQuery的选择器和方法,而
parentElement
是纯javascript的方式。或者,您也可以这样做:
jQuery('.kb content h2').parent().each(function(){…})这个
将引用h2的inner.kb内容的父级。
this.id;
$(obj).attr('id');
...
<div id="test">
    <h2>This is a test</h2>
</div>