![](/img/trans.png)
[英]How to find the name of an object created in a class in Javascript
[英]I cannot find the name of a dynamically created javascript object (in jQuery)
我有一个页面,该页面使用javascript向该页面添加了一些文本框,然后我们稍后会尝试基于这些文本框进行一些工作。
但是,我遇到的麻烦是无法返回使用js保存的“名称”值。
以下是整页的源代码(尽管是简化版)。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="Scripts/jquery-1.4.1-vsdoc.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//we use live because the inputs havent been created yet.
$('.myclass').live('blur', function () {
//debugger;
alert('textbox selected has ID '+ $(this).attr('id') ); //this returns txtInput
alert('textbox selected has name '+ $(this).attr('name') ); //this returns null (or an empty string).
});
AddInputTextBox("My Label: ", "txtInput", "mydiv", "MyName");
});
function AddInputTextBox(LabelValue, Id, divToAddTo, NameKey) {
//debugger;
var txtbox = document.createElement('input');
txtbox.setAttribute("type", "text");
txtbox.setAttribute("id", Id);
txtbox.setAttribute("name", NameKey);
txtbox.setAttribute("class", "myclass");
alert('Textbox created with name = ' + txtbox.name);
var foo = document.getElementById(divToAddTo);
foo.innerHTML += LabelValue;
foo.appendChild(txtbox);
}
</script>
</head>
<body>
<div id="mydiv">
<!-- placeholder -->
</div>
</body>
</html>
如您所见,document.ready运行并创建一个文本框。 当模糊激发时(框失去焦点)-我可以访问ID,类,类型等,但无法获取“名称”的值。
当然这很简单,但是有人可以告诉我为什么吗?
使用IE创建<input>
元素时,必须像这样:
var txtbox = document.createElement('<input name="' + NameKey + '">');
IE不喜欢您更改<input>
的“名称”属性,一旦它存在,因此您必须在调用“ createElement()”时告诉它要做什么。
有人可能想知道为什么不使用jQuery构建动态内容,因为无论如何都已经加载了它。
( 编辑,我认为它是“类型”属性,但现在我认为它是“名称”。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.