0

Im與Boostrap 3和Jquery工作和我試圖切換按鈕內的文本與助推器圖標跨度,但不知道該怎麼做。這是我的嘗試:
的HTML代碼:jquery切換文本按鈕與內部引導程序圖標

<button type='button' class='btn btn-success btn-md'> 
<span class='glyphicon glyphicon-edit'></span> Edit</button> 


jQuery代碼:

$(this).text(function(i, text){ 
    return text === "<span class='glyphicon glyphicon-edit'></span> Close" ? "<span class='glyphicon glyphicon-edit'></span> Edit" : "<span class='glyphicon glyphicon-edit'></span> Close" 
}) 

那麼......怎麼會是這樣的作品?
1)切換文本按鈕但保持相同圖標的示例。
2)另一個切換文本按鈕的例子,但切換圖標類
謝謝。

+1

由於您將原始HTML放入元素,您需要使用'.html'而不是'.text'。 –

+0

最後,我將「編輯」文本放入標記中,以便更換內容。但謝謝你的答案。 – SilverSurfer

回答

1

而不是===您可以使用indexOf因爲:

$(this).text() === "↵  Edit" 

就像你可以看到有一個多餘的字符(新行),你不能靠這個。

與jQuery.html的片段是:

$('button').on('click', function(e) { 
 
    $(this).html(function(i, text){ 
 
    return (text.indexOf("Close") != -1) ? "<span class='glyphicon glyphicon-edit'></span> Edit" : "<span class='glyphicon glyphicon-edit'></span> Close" 
 
    }) 
 
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 

 
<button type='button' class='btn btn-success btn-md'> 
 
    <span class='glyphicon glyphicon-edit'></span> Edit</button>

或者,JS你可能會寫:

this.childNodes[2].textContent = (this.childNodes[2].textContent.indexOf("Close") != -1) ? 
     ' Edit' : ' Close'; 

的片段:

$('button').on('click', function(e) { 
 
    this.childNodes[2].textContent = (this.childNodes[2].textContent.indexOf("Close") != -1) ? ' Edit' : ' Close'; 
 
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 

 
<button type='button' class='btn btn-success btn-md'> 
 
    <span class='glyphicon glyphicon-edit'></span> Edit</button>

0

您應該使用的html()代替text()

$(this).html(function(i, text){ 
    return text === "<span class='glyphicon glyphicon-edit'></span> Close" ? "<span class='glyphicon glyphicon-edit'></span> Edit" : "<span class='glyphicon glyphicon-edit'></span> Close" 
}) 
1

如何:

<button class="btn btn-primary toggle-text" data-toggle="collapse" href="#collapseExample"> 
<span class='glyphicon glyphicon-edit'></span><span>Edit</span><span class="hidden">Close</span>... 

$('.hidden').removeClass('hidden').hide(); 
$('.toggle-text').click(function() { 
    $(this).find('span').each(function() { $(this).toggle(); }); 
}); 

http://jsfiddle.net/bcwhh8cp/