我正在做一个项目,其中有一个无序列表,其中包含标签,当前需要访问 li
的 id我将鼠标悬停在上面,但警报的输出给了我 undefined
或者只是空白。
JavaScript:
$("ul#menu li").mouseover(function(){
var current_id = $(this).attr("id")
alert(current_id);
}
HTML:
<ul id="menu">
<li>
<a class="exclude" id="testvideo1" href="#">1</a>
</li>
<li>
<a class="exclude" id="testvideo2" href="#">2</a>
</li>
<li>
<a class="exclude" id="testvideo3" href="#">3</a>
</li>
</ul>
最佳答案
之所以显示undefined
是因为$(this)
代表li
标签和a
code> 其中包含您要查找的 id
。
也许您可以尝试以下操作:
$('ul#menu li').mouseover(function() {
var current_id = $(this).find('a').attr('id');
alert(current_id);
});
在这里进一步阅读:.find()
基于@AlonEitan的评论最好使用 .children()
而不是 .find()
。在文档中发现以下内容:
The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.
所以你也可以这样做:
$('ul#menu li').mouseover(function() {
var current_id = $(this).children('a').attr('id');
alert(current_id);
});
在这里进一步阅读:.children()
希望这会有所帮助!
关于javascript - 无法在变量 jQuery 中存储元素的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59520503/