2

好的,我知道这应该很简单。我有一个<dl>包含数据定义和数据标签的定义列表 ( )。我在其中一个数据定义中有输入,因此用户可以定义定义。

然后我试图获取该定义的标签名称。在演示中,警报应提示“cycle_3”。

var myErrors = $('.myTest').prev('dt').text();
console.log(myErrors);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>

4

3 回答 3

11
$('.myTest').parent().prev('dt').text();
于 2012-11-14T01:35:07.747 回答
1

采用.closest()

$('.myTest').closest('dd').prev('dt').text();
于 2012-11-14T01:40:23.667 回答
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>

JS 小提琴演示

参考:

于 2021-03-12T21:18:07.030 回答