好的我知道这应该很简单。我有一个包含数据定义和数据标签的列表。我在其中一个数据定义中有输入,因此用户可以定义定义。然后我试图获得该定义的标签名称。在jsfiddle中,警报应提示“cycle_3”http://jsfiddle.net/M6WJp/
<dl>
<dt> cycle_1:</dt>
<dd> test </dd>
<dt> cycle_2: </dt>
<dd> test </dd>
<dt> cycle_3: </dt>
<dd>
<input class="myTest" value="test" />
</dd>
</dl>
var myErrors =$('.myTest').prev('dt').text();
alert(myErrors);
答案 0 :(得分:8)
$('.myTest').parent().prev('dt').text();
答案 1 :(得分:1)
使用 .closest()
$('.myTest').closest('dd').prev('dt').text();
答案 2 :(得分:0)
虽然我提出这个问题的时间非常晚,但值得指出的是,原生 JavaScript 完全有能力实现这一要求:
// here we retrieve the first element in the document which matches the
// selector passed to the document.querySelector() method (this method
// will return either the first matching element-node, or null if no
// element is found):
const input = document.querySelector('input'),
// here we navigate through the DOM from the <input> element found
// previously; we navigate to the first element (if any exists) that
// matches the selector passed to the Element.closest() method, and
// then from that <dd> element to its previous element-sibling,
// using the Node.previousElementSibling property:
inputPreviousDT = input.closest('dd').previousElementSibling;
// here we use a template literal to interpolate the JavaScript expression
// - wrapped in the '${...}' block - into the string itself, to show the
// text-content of that element:
console.log(`The previous <dt> contains the text of: "${inputPreviousDT.textContent}"`);
// here we access the element-node, and use the classList API to
// add an orange background to further - visually - demonstrate
// that the correct <dd> element was found:
inputPreviousDT.classList.add('highlight');
*, ::before, ::after {
box-sizing: border-box;
margin: 0;
padding: 0;
font-size: 1rem;
font-weight: 400;
}
dl {
display: grid;
gap: 0.5em;
grid-template-columns: min-content 1fr;
}
dt {
font-weight: 600;
grid-column: 1;
grid-row: auto;
}
dd {
grid-column: 2;
grid-row: auto;
}
.highlight {
background-color: #f806;
}
<dl>
<dt>cycle_1:</dt>
<dd>test </dd>
<dt>cycle_2: </dt>
<dd>test </dd>
<dt>cycle_3: </dt>
<dd>
<input class="myTest" value="test" />
</dd>
</dl>
参考文献: