使用JQuery获取DT和DD元素的内容

时间:2018-08-05 14:40:51

标签: javascript jquery html

我试图通过单击链接来获取字典术语(DT)及其字典定义(DD)的内容。

目前已采取的步骤:

  1. 将链接的数据跟踪属性设置为DT id
  2. 构造选择器
  3. 使用选择器获取DT 到目前为止成功,但随后...
  4. 更新选择器以获取DD

这是失败的地方:使用更新的选择器的步骤不会返回字典定义的内容 尝试使用“ dd”,“ dd:first”和“ dd:nth-​​child(1)”构造选择器
并更改为“ var definition = $(defSelector).text();”到“ ... val()”和“ ..html()”,但没有一个起作用。

请让我知道您是否可以确定和解释解决方案。

$('.help-lookup').click(function(){

  // get this data-target
  var target = $(this).data("target");
  alert('data target = ' + target);
  //create # + DT selector with target value
  selector = ('#'+target);
  alert('selector= '+ selector);
  //get tile
  var title = $(selector).html();
  //title = $(this).text( title );
  alert (title);
  // create DD selector
  var defSelector = (selector+' dd:first');
  alert(defSelector);
  //get definition
  var definition = $(defSelector).text();
  alert(definition);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<p>
  Goal: clicking "look up" returns html contents of DT and DL<br/>
  Expect: final alert to display: "Definition text"<br/>
  Actual: final alert displays ""
</p>

<a href="#" data-target="TermToLookUp" class="help-lookup">look up</a>

<dl>
  <dt id="TermToLookUp" class="anchor">Term</dt>
  <dd>Defintion text</dd>
</dl>

2 个答案:

答案 0 :(得分:1)

(selector+' dd:first')是错误的。您正在尝试获取selector#TermToLookUp)旁边的元素的文本。因此,请使用.next()方法。

$('.help-lookup').click(function(){

  // get this data-target
  var target = $(this).data("target");
  alert('data target = ' + target);
  //create # + DT selector with target value
  selector = ('#'+target);
  alert('selector= '+ selector);
  //get tile
  var title = $(selector).html();
  //title = $(this).text( title );
  alert (title);
  // create DD selector
  var defSelector = $(selector).next("dd");  // Change here
  alert(defSelector);
  //get definition
  var definition = defSelector.text();  // Change here
  alert(definition);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<p>
  Goal: clicking "look up" returns html contents of DT and DL<br/>
  Expect: final alert to display: "Definition text"<br/>
  Actual: final alert displays ""
</p>

<a href="#" data-target="TermToLookUp" class="help-lookup">look up</a>

<dl>
  <dt id="TermToLookUp" class="anchor">Term</dt>
  <dd>Defintion text</dd>
</dl>

答案 1 :(得分:1)

dd元素不是孩子,而是dt的兄弟姐妹。因此,您的选择器必须是

$(selector).next('dd')