javascript 找到最近的班级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9403719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
find closest class
提问by Leon van der Veen
I want to find a closest class of the given object. My markup looks like this:
我想找到给定对象的最接近的类。我的标记如下所示:
<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>
The jquery looks like this:
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); }
What I want is when I click on the [li] that the value of the clicked [li] gets into the class optionValue.
我想要的是当我点击 [li] 时,点击的 [li] 的值进入类 optionValue。
I want to duplicate this list so it have to work for more lists on one page.
我想复制这个列表,所以它必须在一页上处理更多列表。
I hope someone can help me.
我希望有一个人可以帮助我。
Thanks in advance!
提前致谢!
回答by Jasper
//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());
});
Here is a demo: http://jsfiddle.net/rpVxV/
这是一个演示:http: //jsfiddle.net/rpVxV/
回答by elclanrs
Try this:
试试这个:
$('.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);
});
Your code is basically not working because of this line:
由于这一行,您的代码基本上不起作用:
//`.optionValue` is not IMMEDIATE
// children of `.table_settings`
// so it won't work
$(this).parents('.table_settings').children('.optionValue').text(value); }