HTML5 contentEditable with jQuery

2020-03-01 05:09发布

I have some elements that need to have the text inside editable, for this I am using the HTML 5 attribute contentEditable. I can't seem to do use jQuery for this using multiple selectors. What I want to do is have every tag inside a container div be editable. Here's an example of what it would look like if it worked with jQuery:

$("#container <all tags here>").contentEditable = "true";

I dont know how to make it select all tags but you get the point.

So all span, div, tables, bold, etc should be editable individually

5条回答
我欲成王,谁敢阻挡
2楼-- · 2020-03-01 05:42
$('#container *').attr('contenteditable','true');

* means "all element types", and is analogous to a,div,span,ul,etc...

Like most other jQuery functions, attr applies the same operation to every element captured by the selector.

查看更多
闹够了就滚
3楼-- · 2020-03-01 05:43

I get the impression you're misunderstanding the problem in two places:

  1. jQuery creates "query" objects which provide a shorthand for manipulating sets of DOM elements. Your example code sets contentEditable on the query, not what it matches. You want jQuery's shorthand for "set an attribute on all matching elements", which is $('whatever').attr('contentEditable','true');

  2. I'm not sure you understand contentEditable properly. You're supposed to set it on the top-level container for each editable region and its effects apply to everything within. In my experience, if setting contentEditable on#container or something like #container div.post really isn't good enough, then you've got bigger problems.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-03-01 05:48

For some reason in IE10 only this seemed to work:

$('#container').get(0).contentEditable = "true";

Why attr didn't work I do not know.

查看更多
Luminary・发光体
5楼-- · 2020-03-01 05:50

If I can remember correctly, setting the contentEditable value on the parent would also cause all its children to become editable.

So doing this:

$('#container').attr("contentEditable", "true");

Should work.

查看更多
够拽才男人
6楼-- · 2020-03-01 06:01
$("#container *").attr("contentEditable", true)

Just a guess. Away from workstation.

查看更多
登录 后发表回答