2014-01-16 42 views
0

我想在一些使手風琴展開和摺疊的鏈接文本旁邊添加一個圖標。文本已經從'See more'改變爲'See less'。看到工作演示 - http://bootply.com/106271jquery裏面的HTML標記

因此增加:

<span class="glyphicon glyphicon-chevron-up"></span> 

停止文本變化工作。

這裏是破碎的版本嘗試添加該圖標:http://bootply.com/106270

$(document).ready(function(){ 
    $("#morebtn").click(function(){ 
     $(this).html($(this).html() == "See more <span class="glyphicon glyphicon-chevron-up"></span>" ? "See less" : "See more <span class="glyphicon glyphicon-chevron-up"></span>"); 
    }); 
}); 
+1

'$(this).html('.....')' – Abhitalks

+0

Duplicate http://stackoverflow.com/questions/21159802/link-text-changes-on-click-see-more-see- less-jquery-bootstrap-accordion/21159947#21159947 –

+1

不要替換整個html ...有更好的方法來遍歷DOM。您應該只是替換文本,並更改​​嵌套範圍的類 – series0ne

回答

2

你有不匹配的報價:

"See more <span class="glyphicon glyphicon-chevron-up" ... " 
^     ^       ^ ^

爲了解決這個問題,請使用單引號或轉義雙引號:

'See more <span class=" ... " ... ' 

"See more <span class=\" ... \" ... " 

Working Bootply Demo

2

使用.indexOf()檢查一個特定的詞的可用性。也請記住,不使用"正在由"構建一個字符串的內部,而不是使用'

嘗試,

$(document).ready(function(){ 
    $("#morebtn").click(function(){ 
     $(this).html($(this).html().indexOf("See more") > -1 ? "See less" : "See more <span class='glyphicon glyphicon-chevron-up'></span>"); 
    }); 
    }); 
1

重寫整個網站的HTML內容與

$(this).hmtl(""); 

Isn't一個好主意。

而不是使用的,你在做這樣的:

$(document).ready(function() 
        { 
        $("#morebtn").click(function() 
             { 
              $("#morebtn").val($("#morebtn").val().indexOf("See more") === 1 ? 
                   $("#morebtn").val("See less") 
                   : $("#morebtn").val('See more <span class="glyphicon glyphicon-chevron-up"></span>')); 
             } 
           ); 
        } 
      ); 

另外,值得一提,這條線不能工作:

"See more <span class="glyphicon glyphicon-chevron-up" 

你的JavaScript控制檯應該顯示了語法錯誤。因爲你不能使用隱含的引號來避開內部引用。你要逃避自己內心的雙引號是這樣的:

class=\"glyphicon glyphicon-chevron-up\" 

OR:我強烈建議你使用單引號和雙引號(順序doesn't物質)替代方法,因爲it's更容易進行閱讀人類。它可以是單個或兩個第一個):

'See more <span class="glyphicon glyphicon-chevron-up"></span>' 
// or: 
"See more <span class='glyphicon glyphicon-chevron-up'></span>" 

希望這對你有幫助。