3

我想找到给定对象的最接近的类。我的标记如下所示:

<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。

我想复制此列表,因此它必须适用于一页上的更多列表。

我希望有一个人可以帮助我。

提前致谢!

4

2 回答 2

7
//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/

于 2012-02-22T21:59:17.177 回答
1

试试这个:

$('.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); }
于 2012-02-22T22:14:09.587 回答