1 回答
TA贡献1869条经验 获得超4个赞
您可以使用名为的 HTML属性contenteditable,这将允许用户编辑元素上的 html 内容!但是,如果您需要保存更改,则必须AJAX在PHP页面中添加一些 javascript请求,以便将更改保存到数据库或文件或其他任何内容中。希望我的回答对你有用!
window.isEditingALi=false;
document.addEventListener("click", function(e){ //Of course you can merge this EventListener with the next one but I am separing them just to make things clear for you !
const elementsIdSelector="editableLi";
e=(e||window.event);
e.preventDefault();
const path=e.path;
for(var i=0;i<path.length-4;i++){
if(path[i].tagName=="LI"&&path[i].id==elementsIdSelector){
//Found a Li element with the id required ( Even dynamically created li would fires ! )
//Do whatever you want there
path[i].addEventListener("click", function(){
if(this.getAttribute("contenteditable")!="true"){
const wantEdit=window.confirm("You want to edit this element content ?");
if(wantEdit){
this.setAttribute("contenteditable", true);
window.isEditingALi=this;
this.focus();
}else{
window.isEditingALi=false;
}
}
});
}
}
});
document.addEventListener("click", function(e){
e=(e||window.event);
e.preventDefault();
const path=e.path;
let canGetReset=true;
for(var i=0;i<path.length-4;i++){
if(path[i]==window.isEditingALi) canGetReset=false;
}
if(canGetReset&&window.isEditingALi){
window.isEditingALi.removeAttribute("contenteditable");
//Here you can add your Ajax request or whatever function you want to do after the user finish editing the li ..
alert("Li has been changed successfully !");
window.isEditingALi=false;
}
});
//This is just an additional function to test if the dynamically created element would work or not !
function createEditableLi(){
const ul=document.querySelector("ul");
const newLi=document.createElement("li");
newLi.setAttribute("id", "editableLi");
newLi.innerHTML="New Li (Created dynamically)";
ul.appendChild(newLi);
}
body{
font-family: Arial, sans-serif;
font-size: 14px;
}
You can actually edit these Li by clicking and apply any changes you want ! (Even dynamically created elements are supported now!)
<br>
<ul>
<li id="editableLi"> First Li</li>
<li id="editableLi"> Second Li</li>
<li id="editableLi"> Third Li</li>
<li id="editableLi"> Another Li</li>
<li id="editableLi"> More Li</li>
</ul>
<br>
<button onclick="createEditableLi()">Create a New Li Dynamically</button>
添加回答
举报