![](/img/trans.png)
[英]edit row in html table using php and js/jquery and save it in db
[英]Jquery Edit text then save to DB using ajax
我有一個頁面,以div和spans顯示文本。 在每個圖像旁邊,都有一個用戶可以單擊的圖像。
當他們單擊此圖像時,我需要將文本更改為文本區域,以便用戶可以編輯文本,然后在單擊該文本時,將需要調用php腳本以通過ajax保存到DB。
所有div和圖像具有唯一的ID所以這應該使之與jQuery選擇更容易。
有人可以幫忙嗎? 到目前為止,我嘗試過的所有方法都沒有真正起作用。
謝謝
您可以使div可編輯:
$(".ajax-div .on-img").on("click",function(ev) {
$(this).parent().find(".editable-text").attr("contenteditable", "true").after("<button onclick='saveEdits()'>Save</button>");
})
您的html結構必須看起來像這樣
<div class="ajax-div" id="somediv">
<div class="editable-text">Editable text</div>
<img class="on-img" src="" alt="">
</div>
saveEdits()函數:
function saveEdits() {
$(".ajax-div").each(function() {
if(this.hasAttr("contenteditable") && this.attr("contenteditable")==true) {
id = $(this).attr("id");
//handle change
}
})
}
假設您有:
<div id='mydivparent'>
Some text here
<div>
<img src='images/mypic.jpg' id='mydiv' onclick='editr(this)' />
</div>
</div>
根據您的需求建議,下面的JS代碼就足夠了。
<script>
function editr(obj)
{
var id = $(obj).attr('id');
var text = $('#mydiv'+parent).text();
$('#mydiv'+parent).empty();
$('#mydiv'+parent).append('<form action='form_processor.php' onsubmit="send_ajax($('textarea#'+id+').value)"><textarea id='+id+'>'+text+'</textarea><input type='submit' value='Save Text'></form>');
}
function send_ajax(txtValue){
$.ajax({
url: 'form_processor',
cache: false;
type: 'POST',
data: {'text': txtValue},
success: function(){
//Code to add the text to the div and delete the textarea returning it to a normal div
}
});
return false;
}
</script>
您應該記住如何命名div和images id,以便從image id訪問div的id很容易。 您應該使用自己的協議,這樣如果您具有圖像ID,就可以獲取相關的div ID,或者可以將圖像放入div中,就像選擇父項一樣簡單。
編輯后,您可以在用戶之后將其設置為ajax。
該代碼不能完全涵蓋所有情況,例如,如果在保存第一個打開的文本區域之前單擊另一個圖像,但是我相信它將為您設置正確的方法。
最后,我使用了jeditable插件為找到這篇文章的任何人解決了這個問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.