如何使用 Javascript 访问子元素?
我正在根据用户操作动态创建表单。每个实例都有一个输入框和两个“按钮”。每个实例都将包装在一个唯一的 div 标签中。
我尝试做但没有成功的是,当我动态创建“按钮”时,我附加一个函数,该函数的输入变量包含其实例的 div 。这是一个简短的摘录:
var newDivClass = document.getElementById("instance"+1);
button1.innerHTML = "<a href=\"#\" onclick=\"buttons("+newDivClass+");\" id=\"button1\"> Button1 </a>";
function buttons(selected) {
//I want this to select the first instance
//of button1 found within div newDivClass
selected.getElementById("button1");
//I also tried
//this.getElementById("button1");
//selected.getChildren[0];
}
问题似乎在于将 newDivClass 传递给实际函数。
I am dynamically creating forms dynamically according to a users actions. It is an entry-box and a two "buttons" for each instance. Each instance will be wrapped in a unique div tag.
What I tried to do without success is when I dynamically create the "button" I attach a function with the input variable containing the div of its instance. This a brief excerpt:
var newDivClass = document.getElementById("instance"+1);
button1.innerHTML = "<a href=\"#\" onclick=\"buttons("+newDivClass+");\" id=\"button1\"> Button1 </a>";
function buttons(selected) {
//I want this to select the first instance
//of button1 found within div newDivClass
selected.getElementById("button1");
//I also tried
//this.getElementById("button1");
//selected.getChildren[0];
}
The problem appears to be in passing newDivClass to the the actual function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的目的是将对象的名称作为字符串传递,而不是对对象本身的引用,那么您需要在 newDivClass 变量周围加上引号:
否则,按钮函数中的脚本将尝试在位于 dom 顶层的 id 为“instance*n*”的对象。
If your intent is to pass the name of the object as a string and not a reference to the object itself, then you would need to have enclosing quotes around the newDivClass variable:
Otherwise the script in your buttons function will be attempting to operate on an object with the id "instance*n*" at the top level of the dom.
要获取第一个子级,您可以使用
firstChild
属性。To get the first child, you can use the
firstChild
property.