Javascript 查找最近的类
我想找到给定对象的最近类。我的标记如下所示:Javascript 查找最近的类,javascript,jquery,closest,Javascript,Jquery,Closest,我想找到给定对象的最近类。我的标记如下所示: <div class="table_settings"> <div style="float:left;"> <div class="stats_options" id="yearSelector" style="width:140px;"> <div style="float:left"><span class
<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>
$(".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
我想复制此列表,因此它必须在一页上处理更多列表
我希望有人能帮助我
提前谢谢 //选择作为``元素的子元素的所有`- `元素,该元素是`.options\u list`元素的子元素
//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());
});
$(“.option_list”).children('ul').children()。单击(函数(){
//使用“.table\u settings”类选择第一个祖先元素,
//然后选择`.optionValue`元素,它是`.table_settings`元素的后代,
//然后将其文本设置为所单击的` - `元素中的输入元素的文本
$(this).closest('.table_settings').find('.optionValue').text($(this.children().val());
});
这是一个演示:试试这个:
$('.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); }
嗯,您不能单击div上的“display:none;”将其隐藏-并且没有标记有
class='optionValue'
@Mark
??Jasper,谢谢您的回答,但它没有正常工作。我在页面上使用了更多的列表,当我点击其中一个列表时,我会得到我所有列表中点击列表的值……你必须发布更完整的HTML,以便我诊断哪里出了问题。但是您很可能需要为
元素指定一个类,并将其用作.closest()
选择器,而不是.table\u settings
。很抱歉,我忘记关闭table\u settings。所以你的解决方案奏效了!谢谢