我的问题听起来很简单。我有没有像这样指定 id 和类的 div
<div style="position:relative; float:left">
<input type="text" onfocus="renderCalendar(event);" size="50" id="cal" name="cal">
<div class="wrappercal calwrapper">
<div class="yearmonth">
<table class="caltable"><tbody>
<tr><th width="80%" scope="col" colspan="5">
<select class="dtcombo year" onchange="changeCalendar()">
<option value="2000">2000</option>
<option value="2001">2001</option>
</select>
<select onchange="changeCalendar()" class="dtcombo month">
<option value="1">1</option>
<option value="2">2</option>
</select></th>
</tr>
</tbody>
</table>
</div>
</div>
</div>
页面中可能有几个相似的div
我有一个javascript函数
function renderCalendar(event){
var triggerer=event.target.id; // THIS WILL GIVE THE ID OF TEXTBOX THAT TRIGGERED THIS FUNCTION.
$("#"+triggerer).parent().children(".wrappercal").children(".yearmonth").children(".caltable").children(".year").val(); //not working
}
鸟巢是这样的
Parent Div > wrappercal(div) > yearmonth(div) > caltable(table) > year(select)
我的问题是获取触发函数的文本框父 div 类“year”的组合值。
有人能找出我哪里错了吗?有什么建议吗?
附言请原谅我不擅长 dom 元素。
谢谢
最佳答案
为什么不试试呢?
function renderCalendar(event){
$(event.target).parent().find(".wrappercal .yearmonth .caltable .year").val();
}
你能检查(使用 console.log(event.target)
和跟踪)目标元素真的是它应该在的地方吗?
编辑
问题是 children()
仅搜索一层(深层)子节点并且 .caltable
之间存在多个层级和 .year
(<tr><th>...
)。使用 find()
相反(它将通过您的节点递归搜索)。 ;-)
参见 this了解更多信息。
关于javascript - 如何通过触发函数的元素的父div的类名获取另一个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12550274/