【发布时间】:2016-08-09 22:43:34
【问题描述】:
我的 Js/Rails 代码有问题。我有一个当我单击按钮时动态创建的表单(它可以在同一页面中创建多个这种表单),它包含一个 ID 永远不会相同的选择。我需要根据选择值将一些值放入输入中。在第一种形式中它工作得很好,但后来在其他形式中它不起作用。就像我说的,我无权访问 ID,因为它们是在 rails 中创建的。
HTML
<div class="test">
<div>
<div class="divSelect">
<select id="1470190840697_ad_type">
<option>Element1</option>
<option>Element2</option>
<option>Element3</option>
<option>Element4</option>
<option>Element5</option>
<option>Element6</option>
</select>
</div>
<div class="divInput">
<input type="text">
</div>
</div>
<div>
//This is dynamically created
<div class="divSelect">
<select id="1470190846932_ad_type">
<option>Element1</option>
<option>Element2</option>
<option>Element3</option>
<option>Element4</option>
<option>Element5</option>
<option>Element6</option>
</select>
</div>
<div>
<input type="text">
</div>
</div>
Javascript - jQuery
$('.test').on('change',$('.divSelect').children('select'),function(){
updateTime();
});
function updateTime() {
var tipoPauta = { 'Element1':1,
'Element2':2,
'Element3':3,
'Element4':4,
'Element5':5,
'Element6':6
}
var select = $('.divSelect').children('select');
$('.divInput').children('input').val(tipoPauta[select.val()]);
};
非常感谢!我对这个问题很着迷。
【问题讨论】:
-
使用
on()的委托事件处理程序应该有一个字符串作为第二个参数,而不是一个jQuery集合 -
您可以使用相对路径来获取您需要的元素...例如“找到父表单,然后在此表单中,找到具有X类的孩子”这样您就只能找到最接近您正在使用的选择框的输入文本字段。
-
adeneo 你能解释一下为什么吗?谢谢泰林东!
标签: javascript jquery html ruby-on-rails