我的 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()]);
};
非常感谢!我对这个问题感到疯狂。
最佳答案
正如 @adeneo 提到的,您需要指定一个字符串作为选择器作为第二个参数。另外,为了更新正确的输入元素,您的代码应该类似于
$('.test').on('change', '.divSelect' ,function(){
var $select = $(this).find('select');
updateTime($(this), $select);
});
function updateTime($divelement, $selectelement) {
var tipoPauta = { 'Element1':1,
'Element2':2,
'Element3':3,
'Element4':4,
'Element5':5,
'Element6':6
}
var $input = $divelement.next().children('input');
$input.val(tipoPauta[$selectelement.val()]);
};
关于javascript - 动态创建时如何将 select 的值绑定(bind)到输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38861597/