具有“ column”类的多个元素。 查找哪个列元素包含一个id:idString,返回!column!的索引!包含ID
这是我正在搜索的新的(第3个)html:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Style-Type" content="text/css">
<meta name="generator" content="Amazon.com">
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css" class="dontsplit"> .column *{ padding: 20px; }
</style>
</head>
<body class="calibre" style="margin: 0px; padding: 0px; width: 101024px;">
<div class="calibre67">
<div class="last first column" style="width: 616px; float: left;">
<p class="calibre2" style="padding-top: 8px; padding-bottom: 8px;">
<span class="calibre3">bla , bla etc.</span>
</p>
</div>
<div class="column" style="width: 616px; float: left;">
<div class="calibre1 split">
<p class="calibre2" style="padding-top: 8px; padding-bottom: 8px;">
<span class="calibre3">bla bla etc.</span>
</p>
</div>
</div>
<!-- div contains the ID I want to find, structure of page varies with different files -->
<div class="column" style="width: 616px; float: left;">
<div class="calibre1 split">
</p>
<p class="calibre4" style="padding-top: 8px; padding-bottom: 8px;">
<!-- This is the id I want to find, so the function should return 2 (3rd column). -->
<span id="1P-09761e033cf14df8aeccf069ebe7886e" class="calibre6">Prologue:</span>
</p>
<p class="calibre5" style="padding-top: 8px; padding-bottom: 8px;">
<span class="calibre6">It had been bla, bla etc.</span>
</p>
</div>
</div>
</div>
</body>
</html>
我的代码:
var idString = "O-09761e033cf14df8aeccf069ebe7886e";
function findID(idString) {
$(".column").each(function(index, element){
if ($(this).find('*').attr('id') == idString) {
console.log(index);
return index;
}
});
return;
}
var result = findID(idString);
// should return/log 2
// currently returns/logs nothing
在此示例中,函数应返回2。 我已经尝试了很多建议的组合。
我在做什么错了?
答案 0 :(得分:2)
if ($idString)
将始终返回true
。与其进行检查,不如使用if ($(this).attr('id') == idString)
检查每个元素的 .attr()
。
请注意,该属性实际上并不包含#
,因此您需要从ID变量中删除#
,或使用 .contains()
< / strong>。
这可以在下面看到:
var idString = "O-09761e033cf14df8aeccf069ebe7886e";
function findID(idString) {
$(".column").each(function(index, element) {
if ($(this).attr('id') == idString) {
console.log(index);
return index;
}
});
return;
}
findID(idString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="column">“When the grav emitters are charged"</p>
<p class="column">“It wasn’t that bad this time”</p>
<p class="column" id="O-09761e033cf14df8aeccf069ebe7886e">Chapter 1</p>
<p class="column">“I can monitor engineering from up here”</p>
还要注意,索引是从零开始的。
答案 1 :(得分:1)
您可以使用jQuery .index(selector)
方法。它将返回右侧选择器集合中匹配元素(在左侧)的索引。
表示jQuery集合的选择器,在其中查找元素。
const customer = await makeCall(path, method, data);
var idString = "#O-09761e033cf14df8aeccf069ebe7886e";
function findID(idToSearch) {
return $(idToSearch).index(".column p");
}
var result = findID(idString);
console.log(result);