[英]How to change text for an "a" element when clicked and clicked again
我試圖讓“a”元素在再次單擊時一次又一次單擊或單擊另一個“a”元素時更改文本。 這是我到目前為止的代碼:
$(document).ready(function() {
$("a").click(function() {
$(this).prev().toggle();
if ($(this).val("Show More") {
$(this).text("Show less");
}
else if ($(this).val("Show less")){
$(this).text("Show more");
}
});
});
我認為您想知道單擊時該元素的文本內容是“顯示更多”還是“顯示更少”以將其設置為另一種方式。 所以你應該檢查text()
函數,然后像你所做的那樣設置它。 離開它像:
$(document).ready(function() {
$("a").click(function() {
$(this).prev().toggle();
if ($(this).text() === "Show more") {
$(this).text("Show less");
}
else if ($(this).text() === "Show less"){
$(this).text("Show more");
}
});
});
您需要更改邏輯以處理text
因為a
本身沒有價值。
如果帶有文本的邏輯看起來太脆弱,您也可以依賴某些類或數據屬性
$(document).ready(function() { $("a").click(function() { $(this).prev().toggle(); $(this).text(function(_, text){ return { 'Show More': 'Show Less', 'Show Less': 'Show More' }[text] }) }); });
.content { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content">Content</div> <a>Show More</a>
就像他的評論中提到的 charlietfi .. <a>
標簽沒有val()
函數。
因此,如果您必須比較元素的當前文本。 如果你想像我說的那樣做,你的代碼應該是這樣的:
$('a').on('click', function(e) {
e.preventDefault();
let current_text = $(this).text();
let new_text;
if(current_text === 'Show more') {
new_text = 'Show less';
} else {
new_text = 'Show more';
}
$(this).text(new_text);
})
我會保持簡單:
$(document).ready(function() {
$("a").click(function() {
$(this).prev().toggle();
this.innerHTML = this.innerHTML === "Show more" ? "Show less" : "Show more"
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.