【问题标题】:How to bind the value of select to an input when it's dinamically created如何在动态创建时将 select 的值绑定到输入
【发布时间】: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()]);
};

JSBIN CODE

非常感谢!我对这个问题很着迷。

【问题讨论】:

  • 使用on()的委托事件处理程序应该有一个字符串作为第二个参数,而不是一个jQuery集合
  • 您可以使用相对路径来获取您需要的元素...例如“找到父表单,然后在此表单中,找到具有X类的孩子”这样您就只能找到最接近您正在使用的选择框的输入文本字段。
  • adeneo 你能解释一下为什么吗?谢谢泰林东!

标签: javascript jquery html ruby-on-rails


【解决方案1】:

正如@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()]);
};

【讨论】:

  • 太棒了!我明白了,您的解决方案完美无缺,谢谢!
  • 你能解释一下为什么 $name 变量吗?与普通名称变量有什么区别?
  • 本身没有区别。它只是一种广泛使用的约定,用于在存储 jQuery 对象的变量前加上 $ 符号。普通名称变量用于存储经典的 javascript 对象。它不会以某种方式或其他方式产生影响,而只是一种约定,可以快速了解您是否可以在变量上使用 jQuery 函数。我通常也将上面例子中忘记做的变量归为驼峰式。
猜你喜欢
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多