簡體   English   中英

DOM腳本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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM