关于jquery:获取元素ID – JavaScript

Get Element ID - JavaScript

本问题已经有最佳答案,请猛点这里访问。

我知道li元素中的data-id,但现在我想要li元素的id值。 我怎么能得到这个?尝试:

1
2
 var id = $('li[data-id="KnSubject[StId]"]').id;
 console.log(id); // UNDEFINED

Html代码:

1
2
<li role="treeitem" data-jstree="{"icon" :"glyphicon glyphicon-pencil"}" data-id="KnSubject[StId]" data-values="null" aria-selected="true" aria-level="3" aria-labelledby="j1_4_anchor" id="j1_4" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"><i class="jstree-icon jstree-themeicon glyphicon glyphicon-pencil jstree-themeicon-custom" role="presentation">Type dossieritem (StId)
</li>


1
2
var id = $('li[data-id="KnSubject[StId]"]').attr('id');
console.log(id);


使用attr功能。

1
2
var elem = $('li[data-id="KnSubject[StId]"]');
console.log(elem.attr('id'));
1
2
3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
<li role="treeitem" data-jstree="{"icon" :"glyphicon glyphicon-pencil"}" data-id="KnSubject[StId]" data-values="null" aria-selected="true" aria-level="3" aria-labelledby="j1_4_anchor" id="j1_4" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"><i class="jstree-icon jstree-themeicon glyphicon glyphicon-pencil jstree-themeicon-custom" role="presentation">Type dossieritem (StId)
</li>


仅出于完整性原因:

1
$('li[data-id="KnSubject[StId]"]').get(0).id

.get(0)检索原始JS DOM元素。