[英]jquery .closest().find().first().text() not working
Why the following JS not working on the HTML code? 为什么以下JS无法在HTML代码上运行?
HTML CODE: HTML代码:
<div class="grand-parent">
<div class="uncle">Text to log</div>
<div class="general-random-album-images">
<a href="#" class="base-selector">Link</a>
</div>
</div>
JS CODE: JS代码:
$("a.base-selector").click(function(){
console.log($(this).closest('.grand-parent').find('.uncle').first().text());
});
I dont get the "Text to log" text in log. 我没有在日志中看到“要记录的文本”文本。
This is probably because you wrap your code incorrectly since there is no other reason. 这可能是因为没有其他原因导致您包装了错误的代码。 Use either:
使用以下任一方法:
<script>
$(document).ready(function(){ // So we wait everything is loaded
$("a.base-selector").click(function(){
console.log($(this).closest('.grand-parent').find('.uncle').first().text());
});
});
</script>
or 要么
<script>
$("body").on("click", "a.base-selector" function(){ // We filter
console.log($(this).closest('.grand-parent').find('.uncle').first().text());
});
</script>
Because you must wait everything is loaded. 因为您必须等待,所以所有内容都已加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.