jQuery克隆元素,更改ID然后使用keyup()无法正常工作 [英] Jquery clone element, altering id then use keyup() not working

查看:70
本文介绍了jQuery克隆元素,更改ID然后使用keyup()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:当我克隆时 <div id="#cloneme1">...</div>我明白了 <div id="cloneme2">...</div>,但是.keyup()函数不会读取新的DOM元素

The Problem: When i clone <div id="#cloneme1">...</div> i get <div id="cloneme2">...</div> but the .keyup() function wont read the new DOM elements

$('#btnAdd').click(function() {
      var num= $('.clonedInput').length; // how many "duplicatable" input fields we currently have
      var newNum= new Number(num + 1);      // the numeric ID of the new input field being added

      // create the new element via clone(), and manipulate it's ID using newNum value
      var newElem = $('#cloneme' + num).clone().attr('id', 'cloneme' + newNum);

      // manipulate the name/id values of the input inside the new element
      newElem.children(':first').attr('id', 'alteredguianswer' + newNum)

      // insert the new element after the last "duplicatable" input field
      $('#cloneme' + num).after(newElem);
    });

    $('input[type="text"]').keyup(function(){
                var id = $(this).attr("id"); // variable id = id of current textfield
                var value=$(this).val();  // variable value = value in current textfield
                $("#someplace"+id).text(value);  // edit text elsewhere on page using value
            });


<div>
     <input type="button" id="btnAdd" value="add another name" />
</div>
     <div id="cloneme1" style="margin-bottom:4px;" class="clonedInput">Question:<input type="text" id="guianswer1" value="Answer 1" /></div>

我不明白如何获得读取新克隆元素的功能

I dont understand how to get a function to read the new cloned elements

推荐答案

您要绑定DOM中所有匹配元素的keyup事件,但不绑定将来的元素.

You're binding the keyup event for all matching elements in the DOM, but not future elements.

如果您使用的是jQuery 1.7或更高版本,请尝试使用on

If you're using jQuery 1.7 or later, try using on

$('input[type="text"]').on('keyup', function(){
    var id = $(this).attr("id"); // variable id = id of current textfield
    var value=$(this).val();  // variable value = value in current textfield
    $("#someplace"+id).text(value);  // edit text elsewhere on page using value
});

如果您使用的是早期版本,请尝试使用实时

If you're using an earlier version, try using live

$('input[type="text"]').live('keyup', function(){
    var id = $(this).attr("id"); // variable id = id of current textfield
    var value=$(this).val();  // variable value = value in current textfield
    $("#someplace"+id).text(value);  // edit text elsewhere on page using value
});

这篇关于jQuery克隆元素,更改ID然后使用keyup()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆