![](/img/trans.png)
[英]hide and show element depending of the value of radio-button using dom scripting javascript
[英]DOM Scripting Javascript, set element value
我的目标是通过单击另一个按钮在屏幕上添加一个按钮。 我可以成功添加它们,但是它们为空(即无文本)。
我尝试使用此技术设置值:
addButton.setAttribute("value", "Click Me");
失败了,奇怪的是我能够使用setAttribute函数成功设置元素ID。
然后,我尝试了以下操作:
var x = document.getElementById("buttonId");
x.value="Click Me";
以上导致按钮根本不添加。
也许我缺少了一些东西,但我不知道为什么第一种方法不起作用。
注意:这些按钮都是动态创建的,因此标准:
<input type="button" value="click me"/>
不够。
任何帮助表示赞赏。
function addButton(elementId, value, name, type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = type;
element.value = value; // Really? You want the default value to be the type string?
element.name = name; // And the name too?
var foo = document.getElementById(elementId);
//Append the element in page (in span).
foo.appendChild(element);
}
尝试这个。
小提琴示例: http : //jsfiddle.net/kailashyadav/4Q8Fd/
这是一个与jsfiddle关联的按钮的代码:
$('#createButton').on('click', function () {
var button = document.createElement('button');
button.innerHTML = 'hello';
button.setAttribute('type', 'button');
$('#placeForButton').html(button);
});
注意我设置了innerHTML,因为input
依赖于value
属性, button
依赖于打开和关闭HTML属性。 因此,标签之间的值是设置button
文本的内容。 这将转换为innerHTML
。
我仅使用JQuery将事件绑定到按钮单击。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.