开发者

JQuery 101 - Changing text value

I have a link to hide/display some text:

<a href="javascript:void(0);" id="toggle_status_history">show/hide history<a/>

The corresponding JavaScript looks like this:

$(document).ready(function() {
  $('#toggle_status_history').click(function() {
    if ($('#status_history').is(":hidden")) {
      $('#status_history').slideDown("fast");
    } else开发者_StackOverflow中文版 {
      $('#status_history').slideUp("fast");
    }
  });

It works great, but I'd like to toggle the hyperlink text as well. What do I need to do to modify the 'show/hide history' to show either 'hide history' (if it's currently displayed) or 'show history' if it's currently hidden? Something like this..?

$(document).ready(function() {
  $('#toggle_status_history').click(function() {
    if ($('#status_history').is(":hidden")) {
      $('#status_history').slideDown("fast");
      // SOMETHING HERE TO SET TEXT TO 'HIDE HISTORY'
    } else {
      $('#status_history').slideUp("fast");
      // SOMETHING HERE TO SET TEXT TO 'SHOW HISTORY'
    }
  });

Disclaimer: I have less than an hour of experience with JQuery (and I haven't used JavaScript since the late-90s) - I'm just trying to modify a code sample for my site. I've looked at the API for the toggle() and replaceWith() functions but am not getting it to work. Googling and RTFM'ing hasn't helped me so far.


  $('#status_history').text("Whatever you want it to say");

Have a look at the jQuery Documentation. They have a very good documentation which explains everything, with examples. For example, the .text(str); function is underneath manipulation.


$('#toggle_status_history').text("Show history");


$('#status_history').text("Hide/Show History"); is what you need. The better way of doing such things is using toggle method provided by jQuery, it accepts a list of functions which will be looped on each click. So that you don't need to do is(':hidden')


$('#status_history').val("bla bla bla..");

try this... fn.val() is getting the value of input, select or textarea's value or text ;) fn.val(newValue) is setting new values ;)


$(document).ready(function() {
  $('#toggle_status_history').click(function() {
   $('#status_history').toggle('slow')
   $("#toggle_status_history").text(($("#toggle_status_history").text()=='show')?'hide':'show');
}
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜