найти ближайший класс - PullRequest
3 голосов
/ 23 февраля 2012

Я хочу найти ближайший класс данного объекта.Моя разметка выглядит так:

<div class="table_settings">

          <div style="float:left;">
              <div class="stats_options" id="yearSelector" style="width:140px;">
                  <div style="float:left"><span class="optionValue"></span></div>
                  <div style="float:right; margin-top:11px;"><img src="../images/arrow_down.png" /></div>
                  <div class="clear"></div>
              </div>

              <div id="yearSelectorOptions" class="option_list" style="width:160px; display:none; margin-top:0px;">
                  <ul>
                      <li><input type="radio" name="year" value="2" style="display:none;" alt="Winst en verlies" checked="checked" />Winst en verlies</li>
                      <li><input type="radio" name="year" value="1" style="display:none;" alt="Eindbalans" />Eindbalans</li>
                  </ul>
              </div>
          </div></div>

Jquery выглядит так:

$(".option_list ul li").click(function() 
{


    $(this).children('form input[type="radio"]').prop('checked', true);

    value = $(this).children('input[type="radio"]:checked').attr('alt');
    $(this).parents('.table_settings').children('.optionValue').text(value); }

Что я хочу, это когда я нажимаю на [li], что значение нажал [li] попадает в класс optionValue.

Я хочу продублировать этот список, чтобы он работал для большего количества списков на одной странице.

Я надеюсь, что кто-то может мне помочь.

Заранее спасибо!

Ответы [ 2 ]

6 голосов
/ 23 февраля 2012
//select all the `<li>` elements that are the children of the `<ul>` element that is the child of the `.options_list` element
$(".option_list").children('ul').children().click(function() {

    //select the first ancestor element with the `.table_settings` class,
    //then select the `.optionValue` element that is a descendant of the `.table_settings` element,
    //then set it's text to that of the input element inside the `<li>` element clicked
    $(this).closest('.table_settings').find('.optionValue').text($(this).children().val());
});

Вот демоверсия: http://jsfiddle.net/rpVxV/

1 голос
/ 23 февраля 2012

Попробуйте:

$('.option_list')
.find('li')
.click(function () {
    var $radio = $(this).children(':radio'),
        value = $radio.attr('alt'), // Or `$(this).text()` ...
    $(this)
    .parents('.table_settings')
    .find('.optionValue')
    .text(value);
});

Ваш код в основном не работает из-за этой строки:

//`.optionValue` is not IMMEDIATE 
// children of `.table_settings`
// so it won't work
$(this).parents('.table_settings').children('.optionValue').text(value); }
...