如何在KeyUp上传递表单的id?

时间:2013-11-23 15:34:22

标签: javascript jquery forms onkeyup

关于如何获取onKeyUp的值有很多问题,但是我也希望传递onKeyUp形式的id。我尝试过类似的东西,但它告诉我getId没有定义。

function getId(x){
$('.not').append(x);
}

var word = 'HELP';

$('.why').html("<form class='questions'><input type='text' id='"+word+"' 
name='"+word+"' onkeyup='getId("+word+")'></form> ");

http://jsfiddle.net/evs3A/

也正在进行"+variable+"不良练习,因为我使用它的次数很多;)?感谢你。

3 个答案:

答案 0 :(得分:1)

您可以将其更改为:

$('.why').html("<form class='questions'><input type='text' id='"+word+"' 
name='"+word+"'></form> ");

并在jquery中:

$(document).ready(function(){
    var word = 'HELP';
    $(document).on('keyup', '#' + word, function(){
        $('.not').append(word); //or $(this).attr('id'); if the id is the argument that you want to pass
    });
});

如果要更改要传递的变量,可以使用如下数据值:

<input type='text' id='"+word+"' name='"+word+"' data-something="new_value">

并以此模式进行:

$(document).on('keyup', '#' + word, function(){
        $('.not').append(word);
        var value = $(this).data('something');
    });

答案 1 :(得分:1)

使用jQuery挂钩事件并完全避免问题。试试这个:

var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='" + word + "' 
name='" + word + "'></form> ");

$('.questions input').on('keyup', function(e) {
    $('.not').append(this.id);
});

Example fiddle

答案 2 :(得分:0)

这是一个没有任何jQuery的示例。

<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);

function mInit()
{
    byId('myFormId').addEventListener('keyup', onFormKeyUp, false);
    byId('myFormId2').addEventListener('keyup', onFormKeyUp, false);
}

// this function was attached to the form in the mInit function.
// as a consequence, 'this' reffers to the form itself.
// this.id should give us the id of the form
function onFormKeyUp(e)
{
    alert("Keyup detected in the form with the id: '" + this.id + "'");
}

</script>
<style>
</style>
</head>
<body>
    <form id='myFormId'>
        <input id='textField1'/>
        <br>
        <button>Some button</button>
    </form>
    <form id='myFormId2'>
        <input id='textField2'/>
        <br>
        <button>Some button</button>
    </form>
</body>
</html>