gpt4 book ai didi

javascript - JQuery 选择器返回未定义

转载 作者:太空宇宙 更新时间:2023-11-04 14:27:56 25 4
gpt4 key购买 nike

这段 html 代码是由我的 php 代码生成的,但我是从浏览器的 HTML 代码中复制出来的。

console.log 打印出 undefined。我不知道为什么。像往常一样,这可能是一个非常愚蠢的错误。感谢您的帮助。

$('.show').click(function() {
var id = $(this).attr('id');
var div = $("div#" + id);
console.log(div.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Heading <a href='#' class='show' id='2962'>+</a></h3>
<div class='.slidetoggle' id='2962' style='display: none;'>
<p>Test!</p>
</div>

最佳答案

这是因为 .show 元素是一个 a,而不是 div。选择器错误:

var div = $("a#" + id);

更新:

You are right, but I want to show the div, not the a

在这种情况下,您需要使用 DOM 遍历来查找相关元素。您当前的代码不起作用,因为您有重复的 id 属性。这是无效的,因为它们必须是唯一的。试试这个:

$('.show').click(function() {
$(this).closest('h3').next('.slidetoggle').slideToggle();
});
.slidetoggle { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Heading <a href="#" class="show">+</a></h3>
<div class="slidetoggle">
<p>Test!</p>
</div>

<h3>Another Heading <a href="#" class="show">+</a></h3>
<div class="slidetoggle">
<p>Another Test!</p>
</div>

关于javascript - JQuery 选择器返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44937244/

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