簡體   English   中英

在Javascript中選擇動態創建的單選按鈕組並獲取要顯示的內部文本

[英]Selecting Dynamically Created Radio Button Group in Javascript and getting inner text to show

我使用以下代碼作為函數的一部分動態創建了單選按鈕:

for(var j=0; j<currentQuestion.choices.length; j++){
    var choiceText = currentQuestion.choices[j];
    var newRadioButton = document.createElement("input");
    newRadioButton.name="optionsList";
    newRadioButton.type="radio";
    newRadioButton.value = choiceText;

    newRadioButton.innerHTML = choiceText;
    label.appendChild(newRadioButton);
}

單選按鈕已成功創建,但是仍然存在兩個問題:

1)盡管我在控制台登錄每個單選按鈕時都會顯示,但每個單選按鈕的innerHTML都不會顯示在瀏覽器中。 因此,在瀏覽器中,我看到旁邊有一個單選按鈕,但控制台顯示輸入標簽之間有文本

2)我無法弄清楚如何引用動態創建的單選按鈕,以便以后檢查選擇了哪個按鈕。

我試過了

var radioButtonsGroup = document.label1.optionsList;

要么

var radioButtonsGroup = document.getElementsByName("optionsList");

要么

var radioButtonsGroup = document.getElementsByTagName("inputs");

但它們都返回未定義。

輸入元素不支持內部text / html。 您應該為每個單選按鈕添加一個標簽,並將其與其關聯。 代碼如下:

for(var j=0; j<currentQuestion.choices.length; j++){
    var choiceText = currentQuestion.choices[j];
    var id = "radio-id-" + j;
    var p = document.createElement("p");

    var newRadioButton = document.createElement("input");
    var text = document.createElement("label");
    newRadioButton.name="optionsList";
    newRadioButton.type="radio";
    text.innerHTML = choiceText;
    text.htmlFor = id;

    p.appendChild(newRadioButton);
    p.appendChild(text);

    label.appendChild(p);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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