获取动态创建的输入字段的val() [英] Get val() of dynamically created input field

查看:62
本文介绍了获取动态创建的输入字段的val()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

$('document').ready(function() {

    $('#container').append('<input type="text" id="mystuff"><a href="javascript:void(0);" onclick="javascript:showStuff();">Show stuff</a>');
});

function showStuff() {

    alert($('#mystuff').val());
}

问题是警报说undefined,可能是因为元素mystuff是动态创建的.以前,我对动态创建的元素也遇到过类似的问题.在那些情况下,我可以使用.on(),但是在这种情况下,我认为我不能使用,因为我只想将val()存储到变量中.我没有要绑定到mystuff ...

Problem is the alert says undefined, probably because the element mystuff is dynamically created. I've had similar problems with dynamically created elements before. In those cases I could use .on() but in this case I don't think I can, because I just want to store the val() to a variable. There's no event I want to bind to mystuff...

有什么办法解决这个问题吗?

Any idea how to solve this?

推荐答案

问题是您尚未为容器定义value属性. 通过此代码:

the problem is you have not defined value attribute for the container. by this code:

$('#container').append('<input type="text" id="mystuff" value="info"><a   
href="javascript:void(0);"      
onclick="javascript:showStuff();">Show stuff</a>');

您将获得价值.

alert(document.getElementById("container").innerHTML);

alert(document.getElementById("container").innerHTML);

将返回#container内部的任何内容. 经过测试!

will return whatever inside of #container. tested!

这篇关于获取动态创建的输入字段的val()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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