How to make an element's content editable with

2019-01-14 16:26发布

问题:

How would I make it so the content of an element could be made editable through native JavaScript (DOM) and/or jQuery?

回答1:

Solution to toggle editable on/off using a click handler:

$('button').click(function(){
    var $div=$('div'), isEditable=$div.is('.editable');
    $div.prop('contenteditable',!isEditable).toggleClass('editable')
})

DEMO



回答2:

Javascript:

document.getElementById('IdOfElement').contentEditable='true';


回答3:

Look at this example i've made: http://jsfiddle.net/K6W7J/

JS:

$('button').click(function(){
    $('div').attr('contenteditable','true');
})

HTML:

<button>CLICK</button>
<div>YOUR CONTENT</div>


回答4:

If you use jQuery to add the attribute to the element you should be able to switch between edit mode and 'normal' HTML mode. The contenteditable attribute is supported by all major browsers. Check out http://blog.whatwg.org/the-road-to-html-5-contenteditable for more information.



回答5:

Or you can use this plugin which i have been with no problem any time. it is realy simple and easy to use.

Here an example:

Html:

 <div style="margin: 150px">
    <a href="#" id="username">awesome</a>
</div>

JS

 $('#username').editable({
        type: 'text',
        url: '/post',    
        pk: 1,    
        title: 'Enter username',
        ajaxOptions: {
            type: 'put'
        }        
    });

DEMO