试图通过子访问器获取父子。基本上是尝试通过add__block类获取.block__id。 HTML
select id, substring_index(substring_index(meta_value, ',', n), ',', -1
) as meta_value
from metas join metas on char_length(meta_value) -
char_length(replace(meta_value, ',', '')) >= n - 1
jQuery
<div class="col-12">
<span class="block__id">{{$block->id}}</span>
{{$block->title}}
<span class="add__block">+</span>
</div>
当前我的ID未定义。
答案 0 :(得分:2)
您的逻辑几乎是正确的,但是问题是您要为find()
提供一个函数,而您只需要使用选择器字符串即可:
$(".add__block").click(function() {
var id = $(this).parent().find(".block__id").text();
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12">
<span class="block__id">Block #1</span>
Block title
<span class="add__block">+</span>
</div>
<div class="col-12">
<span class="block__id">Block #2</span>
Block title
<span class="add__block">+</span>
</div>
答案 1 :(得分:1)
我对jQuery不太熟悉,但是对于普通Javascript,这非常简单:
const blocks = document.querySelectorAll('.add__block');
for (const block of blocks) {
block.addEventListener('click', (e) => {
console.log(e.target.previousElementSibling.textContent)
})
}
<div class="col-12">
<span class="block__id">{{$block->id}}</span>
{{$block->title}}
<span class="add__block">+</span>
</div>
答案 2 :(得分:1)
另一种选择是使用prev
方法查找同级对象,该方法可能比去父级对象然后从那里搜索更快。
$('.add__block').click(function(){
var id = $(this).prev('.block__id').text();
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12">
<span class="block__id">Block #1</span>
Block title
<span class="add__block">+</span>
</div>
<div class="col-12">
<span class="block__id">Block #2</span>
Block title
<span class="add__block">+</span>
</div>
答案 3 :(得分:0)
您可以尝试以下方法吗:
$(".add__block").click(function(){
var id = $(".block__id").text();
console.log(id);
});
答案 4 :(得分:0)
点击后,您可以找到parent
元素的.add__block
并在父级中找到相关的.block__id
,如下所示,
$(".add__block").click(function(){
console.log($(this).parent().find(".block__id").text(););
});
答案 5 :(得分:0)
$('.add_block').prevAll('span')