动态创建的文本框未触发模糊事件

时间:2013-04-06 11:40:59

标签: jquery

是否有原因为第一次输入激活了模糊事件。但对于动态生成的文本框,它不会触发。

<input type="text" class="year" />
<div id="t"></div>

<script>
$('.year').blur(function () {
    $('#t').html('<input type="text" id="y" />');
});

$('#y').on('blur', function () {
    alert('hello');
});
</script>
  

检查小提琴http://jsfiddle.net/kynsai/6pfST/

修改

我正在使用以下代码

创建输入
<input type="text" id="rows" />
<div id="form"></div>



 $('#rows').on('blur', function () {
    msg = '<table"><tr><td>Year</td></tr>';
    for (i = 1; i <= $(this).val(); i++) {
        msg = msg + '<tr><td><input type="text" id="Year_' + i + '"></td></tr>';
    }
    msg = msg + '</table>';
    $('#form').html(msg);
});

那为什么这条线不起作用?

  $('input[id ^="Year_"]').on('blur', function () {
    alert('t');

});

提前致谢

3 个答案:

答案 0 :(得分:3)

使用.on()(在新的jQuery中不推荐使用.live())。并将其包装在文档就绪函数中。

$(document).ready(function() {
    $(document).on('focusout','.year', function() {
       $('#t').html('<input type="text" id="y" />');
    }).on('focusout', '#y', function() {
       alert('hello');
    });
});

答案 1 :(得分:0)

尝试以下代码...使用实时功能

<script>
$('.year').live('blur',function () {
    $('#t').html('<input type="text" id="y" />');
});

</script>

答案 2 :(得分:0)

尝试将#y的模糊事件放在.year的模糊事件中,因为它在事件之外无法正常工作,因为它尚未放入您的html中,所以请尝试以下代码:< / p>

$('.year').on('blur',function () {
    $('#t').html('<input type="text" id="y" />');

    $('#y').on('blur', function () {
        alert('hello');
    });
});
相关问题