[英]DOM Scripting Javascript, set element value
I am aiming to add a button to the screen through the click of another button. 我的目标是通过单击另一个按钮在屏幕上添加一个按钮。 I can successfully add them but they are blank (ie, No text).
我可以成功添加它们,但是它们为空(即无文本)。
I tried setting the value with this technique: 我尝试使用此技术设置值:
addButton.setAttribute("value", "Click Me");
This failed, the strange thing is I was able to successfully set the elements ID with the setAttribute function. 失败了,奇怪的是我能够使用setAttribute函数成功设置元素ID。
I then tried the following: 然后,我尝试了以下操作:
var x = document.getElementById("buttonId");
x.value="Click Me";
The above caused the button not to add at all. 以上导致按钮根本不添加。
Maybe I'm missing something but I can't think why the first method wouldn't work. 也许我缺少了一些东西,但我不知道为什么第一种方法不起作用。
Note: These buttons are all created on the fly so the standard: 注意:这些按钮都是动态创建的,因此标准:
<input type="button" value="click me"/>
won't suffice. 不够。
Any help appreciated. 任何帮助表示赞赏。
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);
}
Try this. 尝试这个。
Example fiddle: http://jsfiddle.net/kailashyadav/4Q8Fd/ 小提琴示例: http : //jsfiddle.net/kailashyadav/4Q8Fd/
Here is the code for a button, associated jsfiddle : 这是一个与jsfiddle关联的按钮的代码:
$('#createButton').on('click', function () {
var button = document.createElement('button');
button.innerHTML = 'hello';
button.setAttribute('type', 'button');
$('#placeForButton').html(button);
});
Note I set the innerHTML, because an input
relies on a value
attribute, a button
relies on an open and closing HTML attribute. 注意我设置了innerHTML,因为
input
依赖于value
属性, button
依赖于打开和关闭HTML属性。 Therefore, the value in between the tags is what sets the button
text. 因此,标签之间的值是设置
button
文本的内容。 This translates into innerHTML
. 这将转换为
innerHTML
。
I only used JQuery to bind an event to the button click. 我仅使用JQuery将事件绑定到按钮单击。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.