2011-04-07 61 views

回答

14

不知道怎麼了JsFiddle.net,但我不能發佈演示。

你在彼此(.click().toggle())嵌套兩種功能,並.toggle()處理一個click,這樣可能會導致衝突。此外,使用text()代替html()

HTML

<a href="#" id="showMore">Before</a> 

的JavaScript

$('#showMore').toggle(function() { 
    $(this).text('Before'); 
}, function() { 
    $(this).text('After'); 
}); 
+4

「這種方法的簽名是用jQuery的1.8棄用,在jQuery的1.9去除。」 https://api.jquery.com/toggle-event/ 它現在所做的只是將點擊的對象設置爲視線外的動畫。 – gl03 2015-11-01 21:30:07

+3

它不適用於我 – 2016-09-25 04:11:26

+0

不工作,絕對不工作 – 2017-06-23 06:24:07

1

,因爲你是一個嵌套的內部<a>另外,導致像<a href="#" id="#showMore"><a href="">After</a></a>

你應該只使用$(this).text('After')和之前一樣

我想你想使用replaceWith()這在這種情況下效率不高,因爲只有文本發生了變化。

++在其他答案中發現的切換錯誤。對他們的榮譽;-)

3

要綁定一個click<a/>,比裏面的所綁定一個toggle()它。

如果你只是想切換,你可以離開click()

$('#showMore').toggle(
    function() { 
     $(this).html('<a href="#">After</a>'); 
    }, 
    function() { 
     $(this).html('<a href="#">Before</a>'); 
}); 

有了這樣說你把另一<a/>內的<a/>真的是你想要的嗎?或者你只是想替換.text().text("Before")

Jsfiddle example of toggle()

16

攪拌機有相應的答案,但我們也可以推廣你的問題變成一個簡單的jQuery插件:

$.fn.toggleText = function(t1, t2){ 
    if (this.text() == t1) this.text(t2); 
    else     this.text(t1); 
    return this; 
}; 

您的代碼將然後看起來像:

$('#showMore').click(function(){ 
    $(this).toggleText('Before', 'After'); 
}) 
+0

發現它有用,與其他答案不同。 – 2014-12-21 16:26:26

+1

根據OP試圖做的目的,這應該是被接受的答案。 (對不起,拖動一個2歲的職位) – 2015-05-08 21:11:33

12

點擊後切換的簡單解決方案:

$('#showMore').on('click', function(){ 
    $(this).html() == "after" ? $(this).html('before') : $(this).html('after'); 
}); 
+0

應該使用===而不是== – 2017-06-17 07:32:48

1

這是同一個答案的簡化/「更緊湊」版本:"A simple solution for toggling after a click"

$('#showMore').on('click', function(){ 
    $(this).html($(this).html() == 'after' ? 'before' : 'after'); 
}); 

當然這需要jQuery插件才能工作。

+0

此代碼可能工作,但它做出了一個糟糕的答案,因爲它沒有描述它是什麼或它如何回答問題或爲什麼問題中的代碼不起作用。 – AdrianHHH 2014-05-10 19:53:27

+0

請爲您的代碼添加一些解釋,以使其成爲有益健康的答案 – kolossus 2014-05-10 20:00:39

0
jQuery.fn.extend({ 
    toggleText: function (a, b){ 
     var that = this; 
      if (that.text() != a && that.text() != b){ 
       that.text(a); 
      } 
      else 
      if (that.text() == a){ 
       that.text(b); 
      } 
      else 
      if (that.text() == b){ 
       that.text(a); 
      } 
     return this; 
    } 
}); 

用途爲:

$("#YourElementId").toggleText('After', 'Before');