首页 > 解决方案 > Get content of DT and DD elements with JQuery

问题描述

I am trying to get the contents of an Dictionary Term (DT) and it's Dictionary Definition (DD) by clicking a link.

The steps taken so far:

  1. set link's data-track property to DT id
  2. construct selector
  3. use selector to get DT Successful so far, but then...
  4. update selector to get DD

This is where it fails: the step using the updated selector does not return the contents of the Dictionary Definition Tried constructing selectors with "dd", "dd:first", and "dd:nth-child(1)"
and changing "var definition = $(defSelector).text();" to "...val()" and "..html()" but none of those worked.

Please let me know if you can identify and explain a solution.

$('.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>

标签: javascriptjqueryhtml

解决方案


(selector+' dd:first') is wrong. You are trying to get the text of the element that is right next to the selector (#TermToLookUp). So use the .next() method.

$('.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>


推荐阅读