2013-05-06 5 views
0

Когда я нажимаю на одну из кнопок, все <p>s только в инкапсулирующем div должны быть заданы желтым фоном.
В идеале я хотел бы видеть $(this), parent и соответствующий элемент селектора в селекторе jquery. Обновление: Извините, я не сделал мой запрос очищенным.
Я хотел бы видеть селекторов родительского div, элементы, которые я хотел бы выбрать в родительском и $(this) все в разделе select.
Допустим, вы хотите получить <p> элементы из .left div, вы можете расширить положение селектора, как этот
$("p", ".left") - получает все <p> в .left
В моем случае, я хотел бы заполучить .left с помощью $(this), в то время как это " это кнопка. Должно быть в линиях
$("p", $(this).closest("body > div"))Получить все соответствующие элементы в ближайшем родителе

Heres the jsFiddle
кода.

<style> 
    div p.painted { 
     background-color: #FF0; 
    } 
    </style> 
    <div class="left"> 
     <div class="actions"> 
      <div class="ui"> 
       <div class="colors"> 
        <button class="paint">Paint it yellow!</button> 
       </div> 
      </div> 
     </div> 
     <p> 
      Lorem Ipsum 
     </p> 
     <p> 
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. 
     </p> 
    </div> 
    <div class="right"> 
     <div class="actions"> 
      <div class="ui"> 
       <div class="colors"> 
        <button class="paint">Paint it yellow!</button> 
       </div> 
      </div> 
     </div> 
     <p> 
      Lorem Ipsum 
     </p> 
     <p> 
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. 
     </p> 
    </div> 

    <script> 
    $(function(){ 
     $(".paint").click(PaintIt); 
    }); 

    function PaintIt(){ 
     $(this).closest("p").addClass("painted"); 
    } 
    </script> 

ответ

4

Вы можете использовать siblings() вместо ближе, чтобы выбрать все <p>s. здесь обновляется fiddle.

+0

+1 за правильный ответ на мой "некорректные" вопрос. Виноват. Я обновил вопрос, чтобы отразить то, что я точно хочу. –

+1

Хм. Это то, что вы имеете в виду?? Не можете ли вы добавить еще один класс в левый/правый div, чтобы получить их с помощью ближайшего()? Например: http://jsfiddle.net/fkTpu/6/ –

+0

Да, могу. Просто не хочу загрязнять мою уже раздутую страницу html. Также я изучаю различные способы выбора элементов. Следовательно, указано, что быть в селекторах. –

1

closest выбирает ближайший родительский выбранного элемента, согласно разметке, сначала вы должны выбрать родительский элемент, затем выберите/найти элементы абзаца.

$(this).closest("div").siblings('p').addClass("painted"); 

или:

$(this.parentNode).siblings('p').toggleClass("painted"); 

или:

$(this.parentNode).closest('div').find('p').toggleClass("painted"); 

http://jsfiddle.net/nKPFv/

0

На самом деле это работает $("p", $(this).closest("body > div"))
не знаю, почему это было не во время тестирования его!

Updated jsFiddle

Смежные вопросы