[英]Addclass after desired element in jQuery
我想在jQuery中做addClass,
當我嘗試使用以下代碼時,結果類似於圖像1
$('#contineButton').html('Continue').addClass('fa fa-chevron-right');
$('#contineButton').html('Continue').after().addClass('fa fa-chevron-right');
但是,想要得到如下圖2所示的結果
原始按鈕代碼:
<button type="button" class="btn btn-success next-step" id="contineButton">
${vo.continueButtonText} <i class="fa fa-chevron-right"></i>
</button>
您正在使用after()並且應該使用append()
$('#contineButton').html('Continue').append('<i class="fa fa-chevron-right"></i>');
說明:
您在第一次嘗試中使用html-> addClass wich會將類添加到當前對象(按鈕),而在第二次嘗試中(帶有after)將嘗試在隨后插入的空元素中進行操作。 html
完全替換了按鈕的內容,因此<i>
不再存在。
試試這個:
document.getElementById('contineButton').insertAdjacentHTML('beforeend', '<i class="fa fa-chevron-right"></i>');
但這可以通過CSS實現。
要在標簽之前添加文本,您需要使用.before
jquery函數:
$('#contineButton i').before('Continue');
對於您的情況,您需要用新的文本字符串替換文本:
$('#contineButton').contents()[0].remove();
$('#contineButton i').before('Continue');
編輯:這僅在您使用Bootstrap的情況下有效
您為什么要嘗試使用jQuery實現這一目標?
應該與此html / css代碼一起使用。
<!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <button type="button" class="btn btn-success btn-lg"> Button <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> </button>
<button type="button" class="btn btn-success next-step" id="contineButton">${vo.continueButtonText} <i class="fa fa-chevron-right"></i>
</button>
$(document).ready(function() {
$('#contineButton').contents().filter(function() {
console.log(this)
return this.nodeType == 3;
})[0].nodeValue = "The text you want to replace with"
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.