假设我有这样的东西
<div class="xx" data-id="tid">Jumbo Jet</div>
<div class="press"> clickme </div>
<div class="foo">
....
</div>
<div class="xx" data-id="tid">Hello World</div>
<div class="xx" data-id="tid">Red Brown Fox</div>
是否有一个jquery函数会在其下(而不是其子级)搜索特定的ID,然后返回第一个结果。在这种情况下,我应该得到“ Hello World”。查找方法行得通吗? 我正在做这样的事情
$(".press").click(function () {
var item = $(this).find("#tid");
//Get the classname
var name = item.attr('class'); //returns undefined should return xx
//Also how do I return the content ? "Hello World"
console.log(name);
});
关于我在这里做错什么的任何建议吗?
答案 0 :(得分:1)
考虑:
id属性为HTML元素指定唯一ID(值 在HTML文档中必须是唯一的。
更新:您可以使用nextAll()在当前元素下查找并通过其data属性获取元素并过滤第一个匹配项。
您可以尝试以下方法:
$(".press").click(function () {
var item = $(this).nextAll('[data-id="tid"]:first')
var name = item.attr('class')
var content = item.html() // html() get the html content
console.log('class name:', name);
console.log('content:', content);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="xx" data-id="tid">Jumbo Jet</div>
<div class="press"> clickme </div>
<div class="foo">
....
</div>
<div class="xx" data-id="tid">Hello World</div>
<div class="xx" data-id="tid">Red Brown Fox</div>
答案 1 :(得分:1)
如果您想使用诸如id之类的东西但不存在冲突,我建议您使用data-id。
if any(answer != 'y' for answer in user):
print('Sorry')
else:
print('Congratulations')
$(".press").on("click", function(){
var content = "";
content = $(this).next("[data-id='tid']").html();
console.log(content);
});
.press:hover {
cursor: pointer;
background: orange;
}
答案 2 :(得分:0)
id属性应该是唯一的,而不是重复的。 您可以使用同名的类。
id属性为HTML元素指定唯一ID(值 在HTML文档中必须是唯一的)。 https://www.w3schools.com/html/html_id.asp
$(".press").click(function () {
var item = $(this).next(".xx");
//Get the classname
var name = item.attr('class'); //returns undefined should return xx
//Also how do I return the content ? "Hello World"
console.log(name);
console.log(item.text());
});