admin管理员组

文章数量:1405393

Given the following html for a type of blog post editor:

<div class="entry">  
  <div class="title" contenteditable="true">
    <h2>Title goes here</h2>
  </div>
  <div class="content" contenteditable="true">
    <p>content goes here</p>
  </div>
</div>  

I'm trying to use jquery to select the .title and .content divs to attach unique event handlers to each.

$('[contenteditable]').on(...);

works for both but

$('[contenteditable] .title').on(...);

or

$('.title').attr('contenteditable', 'true').on(...);

both don't work to select the specific contenteditable block.

Given the following html for a type of blog post editor:

<div class="entry">  
  <div class="title" contenteditable="true">
    <h2>Title goes here</h2>
  </div>
  <div class="content" contenteditable="true">
    <p>content goes here</p>
  </div>
</div>  

I'm trying to use jquery to select the .title and .content divs to attach unique event handlers to each.

$('[contenteditable]').on(...);

works for both but

$('[contenteditable] .title').on(...);

or

$('.title').attr('contenteditable', 'true').on(...);

both don't work to select the specific contenteditable block.

Share Improve this question edited Feb 16, 2015 at 2:32 Josh Crozier 241k56 gold badges400 silver badges313 bronze badges asked Nov 7, 2013 at 18:58 PirijanPirijan 3,5993 gold badges20 silver badges29 bronze badges 1
  • The contenteditable attribute isn't a Boolean attribute so in theory you should to select a specific attribute value: $('[contenteditable="true"]'). I imagine your version probably works though. – Tim Down Commented Nov 8, 2013 at 9:35
Add a ment  | 

2 Answers 2

Reset to default 3

You could use the attribute selector in CSS .title[contenteditable="true"].

jsFiddle example

.title[contenteditable="true"] {
    background: red;
}

In jQuery: $('.title[contenteditable]').css("background","red")

jsFiddle example

For the first example you have to remove the space between the attribute selector and the class selector, as a space implies descendance.

$('[contenteditable].title').on("click", function(){
    $(this).css('color', 'orange'); 
});

Example: http://jsfiddle/2Bsk4/

本文标签: javascriptSelecting specific contenteditable divs with jQueryStack Overflow