简体   繁体   中英

Changing Text Using jQuery

What I'm trying to do is add a [+] or [-] sign to an expandable heading so that once the user clicks on the heading, its content part will be shown and its sign part will change from + to - and vice versa. Since there are multiple headings, I used jQuery's next() . So far the .content toggling works well, but for some reason the sign is not changing.

<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery(".content").hide();

  jQuery(".heading").click(function()
  {
    jQuery(this).next(".content").toggle();
    if (jQuery(this).next(".sign").text()=="[+]")
    {jQuery(this).next(".sign").text("[-]");}
    else
    {jQuery(this).next(".sign").text("[+]");}

  });
});
</script>

for (int i = 0; i < nodes.getLength(); i++)
 {
   Element element = (Element) nodes.item(i);
   NodeList title = element.getElementsByTagName("Title");
   Element ttl = (Element) title.item(0);
   String linkTitle = getCharacterDataFromElement(ttl);
   htmlReturn += "<a href='#' class='heading'><h4>" + linkTitle + " <span class='sign'>[+]</span></h4></a>";
   htmlReturn += "<div class='content'>";

    ...

}

Because the sign is a descendant element of the heading, not a sibling, use find instead of next :

var sign = jQuery(this).find(".sign");
sign.text(sign.text() === "[+]" ? "[−]" : "[+]");
// Note: A minus sign (−) has the same width as a plus sign (+),
// whereas a hyphen (-) is typically narrower.
if (jQuery(".sign").text()=="[+]")
{jQuery(".sign").text("[-]");}
else
{jQuery(".sign").text("[+]");}

Well, next() only gets the immediate sibling. Try using closest() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM