找到最接近的类

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]的值能够传递到class为optionValue的选项中。
我希望能够复制此列表,以便在同一页上使用多个列表。
希望有人能够帮助我。
提前致谢!

你不能点击它,“display:none;”在div上使其隐藏 - 并且没有标记具有class ='optionValue' - Mark Schultheiss
@Mark <span class="optionValue">?? - elclanrs
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/


Jasper,谢谢你的回答,但它没有正常工作。我在页面上使用了更多这样的列表,当我点击其中一个列表时,我会在所有列表中得到所点击列表的值... - Leon van der Veen
你需要发布更完整的HTML代码,以便我诊断出问题所在。但是很可能你需要给<div style="float:left;">元素赋予一个类,并将其用作.closest()选择器,而不是使用.table_settings - Jasper
对不起,我忘记关闭table_settings的</div>标签了。所以你的解决方案有效!谢谢。 - Leon van der Veen

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); }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接