开发者

Change element's text or HTML after a click

I want to change span element's text with click:

$('.int-bank h2 span').text('Open List');
$('.int-bank 开发者_JAVA百科h2').bind("click", function (e) {
    $(this).next("p").toggleClass("lblock");
    var spn = $(this).find("span");
    spn.text('Close List');
});

But in the second click, the span's text does not change to "Open List". How can I do this?


Too bad there's no toggleText() ;-). You'll have to check the value yourself:

spn.text(spn.text() == 'Open List' ? 'Close List' : 'Open List');

Hey, while I'm at it, why not make a toggleText():

$.fn.toggleText = function (text1, text2) {
    var curText = this.text();
    this.text(!$.trim(curText) ? text1 : 
        (curText == text1 ? text2 : text1));
    return this;
};

Then simplify your code like so:

$('.int-bank h2 span').text('Open List');
$('.int-bank h2').click(function () {
    $(this).next('p').toggleClass('lblock');
    $(this).find('span').toggleText('Open List', 'Close List');
});


That's because you're never setting it to 'Open List' in the click.

$('.int-bank h2').bind("click", function (e) {
   $(this).next("p").toggleClass("lblock");
   var spn = $(this).find("span");
   spn.text(spn.text() === "Close List" ? "Open List" : "Close List");
});

Aside:If you're striving for brevity, you can just use the click handler:

$('.int-bank h2').click(function (e) {
   $(this).next("p").toggleClass("lblock");
   var spn = $(this).find("span");
   spn.text(spn.text() === "Close List" ? "Open List" : "Close List");
});


Slightly more readable option:

$('.int-bank h2').toggle(function () {
      $(this).find("span").text('Close List');
}, function () {
      $(this).find("span").text('Open List');
});


$('.int-bank h2').click(function(e) {
  $(this).next("p").toggleClass("lblock");

  var spn = $("span", this);
  if (spn.text() == 'Open List') {
    spn.text('Open List'); 
  } else {
    spn.text('Close List');
  }
});


I wouldn't change the text. As you are already changing the CSS class of the container...

Instead, I'd make 2 elements, one with each text (or any html you like), and give each a CSS class.

Change the CSS so that only one of them is visible at a time, depending on the CSS class of the parent.

For example using the classes "lblock-on" and "lblock-off":

<style type="text/css">
  .lblock-on { display: none }
  .lblock .lblock-off { display: none }
  .lblock .lblock-on { display: block }
</style>

provided the .lblock-onelement is a block element; otherwise change "display: block" to "display: inline". ("display: inherit" works on Firefox but not on MSIE.)


<script>
$(document).ready(function(){
    var text=$('.int-bank h2 span').text();
    $(this).next("p").toggleClass("lblock");
    if(text=="Open List")
        $('.int-bank h2 span').text('Close List');
    else
        $('.int-bank h2 span').text('Open List');
})

This is one way.........

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜