2013-06-02 3 views
3

Когда пользователь нажимает на мой элемент span с текстом «показать больше». Я хочу, чтобы текст внутри элемента изменился на «Показать меньше».Как переключить текст в элементе с помощью события click

$("div.fluid.examples span.fluid").click(function(e) { 
    this = $(this); 
    d = $(this).prevAll("div.fluid.examples p.hiddenp").length; 
    if (d>0) { 
     this.text("Show Less") 
    } else if (d<0) { 
     this.text("Show More") 
    } 
    $(this).prevAll(".hiddenp").fadeToggle(600); 
}); 

jsfiddle

ответ

2

Почему бы просто не сделать это обычным способом, переключив текст и элементы на один и тот же клик?

$("div.fluid.examples span.fluid").click(function() { 
    $(this).text(function(_,txt) { 
     return txt == 'Show Less' ? 'Show More' : 'Show Less'; 
    }); 
    $(this).prevAll(".hiddenp").fadeToggle(600); 
}); 

FIDDLE

+0

Ah, * sanity * ... +1 –

+1

Может ли это не быть написано '$ (this) .text ($ (this) .text() ==" Показать меньше "?" Показать больше ":" Показать меньше ") 'вместо функции? – mplungjan

+0

@mplungjan - да, может, но, если это нужно, это вопрос мнения, я думаю. – adeneo

2

Here's a working jsFiddle.

Вы должны проверять количество, которые являются visible:

d = $(this).prevAll("div.fluid.examples p.hiddenp:visible").length; 

(Вы просто нужно добавить был :visible бит)

Тогда , в вашем i е:

if (d === 0) { // They're hidden  
    thhis.text("Show Less"); 
} 
else if (d > 0) { // They're not hidden  
    thhis.text("Show More"); 
} 

Или, вместо того, чтобы, если вы могли бы использовать:

thhis.text (d === 0 ? "Show Less" : "Show More"); 

jsFiddle here.

+1

Я установил несколько вещей в вашем [ jsFiddle] (http://jsfiddle.net/nUrSs/6/). – Cary

+0

@CaryHartline Cheers, было немного поспешным усилием. – lifetimes

+1

Мне тоже нравится ваш ответ, если я могу принять 2 ответа, я обязательно приму ваше, спасибо. – user1119742

0

Попробуйте

$("div.fluid.examples span.fluid").click(function (e) { 
    thhis = $(this); 

    d = $(this).prevAll("div.fluid.examples p.hiddenp").length; 
    var $text = thhis.text(); 
    if (d > 0) { 
     $text.indexOf('Show Less') > -1 ? thhis.text("Show More") 
             : thhis.text("Show Less"); 
    } else if (d < 0) { 
     thhis.text("Show More") 
    } 
    $(this).prevAll(".hiddenp").fadeToggle(600); 

}); 

Check Fiddle

0
$("div.fluid.examples span.fluid").click(function(e) { 
    if($(this).text() == "Show More"){ 
     $(this).text("Show Less"); 
    }else{ 
     $(this).text("Show More"); 
    } 

    $(this).prevAll(".hiddenp").fadeToggle(600); 

}); 

Рабочий примерhttp://jsfiddle.net/nUrSs/5/

Вы можете также подкручивать код с тройной оператор:

$("div.fluid.examples span.fluid").click(function(e) { 
    var $this = $(this); 
    $this.text($this.text() == "Show More" ? "Show Less":"Show More"); 

    $(this).prevAll(".hiddenp").fadeToggle(600); 
});