[英]Change text of td element when click on it using jquery
我正在輸出中獲取Json數據,並使用edit選項將其附加到表中,所以我想要的是單擊td的Edit,然后單擊td元素文本應從“ Edit”更改為“ Save”,然后再次單擊“ save”更改為編輯,但是一次,一個td元素應一次從“編輯”更改為“保存”,只有一個“保存”應處於活動狀態,而其他元素保持為“編輯”。
<table class="append_data">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
<th>Action</th>
</tr>
</table>
//獲取數據的腳本:
$.ajax({
url: "<?= base_url('controller/get_users') ?>",
type: 'POST',
data: {
},
success: function (myJSON) {
var output = myJSON;
var html = '';
$.each(output, function (key, value) {
html += '<tr>';
html += '<td>' + value.name + '</td>';
html += '<td>' + value.mobile + '</td>';
html += '<td>' + value.id + '</td>';
html += '<td><a href="javascript:void(0);" style="text-decoration:none;" class="edit_user" data-id="' + value.id + '"><span class="change_res' + value.id + '">Edit</span></a></td>';
html += '</tr>';
});
$('.append_data tbody').append(html);
},
error: function (xhr) {
alert(xhr.status);
}
});
//更改文字的腳本
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$(this).text('Save').siblings().text('Edit');
});
得到輸出:
預期產量:
你可以試試
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$('.edit_user').not(this).text('Edit'); // back all the edit_user to Edit but not this
$(this).text(($(this).text().trim() == 'Save') ? 'Edit' : 'Save'); // change the text for this between Edit or Save
});
說明 :
$('.edit_user').not(this).text('Edit');
返回所有其他元素文本以進行編輯
$(this).text().trim() == 'Save') ? 'Edit' : 'Save'
$(this).text().trim() == 'Save') ? 'Edit' : 'Save'
是if語句..的.trim()
方法,表示如果元素的文本為Save
則將其設置為Edit,反之亦然..大約.trim()
此處仔細檢查文本是否正確等於弦
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.