gpt4 book ai didi

javascript - 如何从父元素获取 ID 作为字符串并与另一个字符串进行比较?

转载 作者:行者123 更新时间:2023-11-28 04:18:19 25 4
gpt4 key购买 nike

我有以下 HTML 结构:

<div id="blah">
<ul style="...">
<li><a href="...">...</a></li>
</ul>
</div>

我有一个针对所有 <a> 的 jQuery 选择器标签。但是,我想检查是否单击了 <a>id="blah" 的子项目.

这是我目前所拥有的:

$(document).on('click', 'a', function(t) {
console.info($(this).text());
if($(this).parent() == 'blah'){
console.info('Yes, this link has the parent');
}
});

然而,if永远不会变成真的,我无法检测到链接何时具有指定的父级。我该如何正确执行此操作?

最佳答案

使用attr()获取元素属性值

if($(this).parent() == 'blah'){

应该是

if($(this).parent().attr('id') == 'blah'){

$(document).on('click', 'a', function() {
console.info($(this).text());
if ($(this).parent().attr('id') == 'blah') {
console.info('Yes, this link has the parent');
}

return false; // To stop page redirection
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blah">
<ul style="...">
<li><a href="...">...</a>
</li>
</ul>
</div>


你也可以使用

if($(this).parent().is('#blah'){

I would like to check if the clicked is a child item of the id="blah".

if ($(this).parent('#blah').length) {

如果您想检查祖先,这将检查直接父级

if ($(this).closest('#blah').length) {

关于javascript - 如何从父元素获取 ID 作为字符串并与另一个字符串进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32883428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com