如何用JS创建单选按钮

how to create radio buttons by JS.

本文关键字:单选按钮 创建 JS 何用      更新时间:2023-09-26

我有一些问题动态创建单选按钮。在我的问题中,我从服务器请求json格式的数据,而不是我检查它是否包含我必须创建单选按钮的选项,否则只需创建字段的TXT区域来提交答案。然后再解析成json格式发送到服务器如果我的问题是写,我会得到下一个问题的新url等等。我的问题是如何创建单选按钮并从中读取数据,然后解析该数据,如{"answerswer": "something"}。我的代码如下:

enter code herefunction loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
  console.log(this.responseText);
  var data = JSON.parse(this.responseText);
  document.getElementById("my_test").innerHTML  = data.question;
  // Send the answer to next URL
  if(data.alternatives !== null){
    createRadioElement(div,);
  }
  var answerJSON = JSON.stringify({"answerswer":"2"});
  sendAnswer(data.nextURL, answerJSON)
   }
 };
 xhttp.open("GET", url, true);
 xhttp.send();
 }
function sendAnswer(url, data) {
  xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.onreadystatechange = function () {
   if (xhr.readyState == 4 && xhr.status == 200) {
      var data = JSON.parse(this.responseText);
      console.log(this.responseText);
      loadDoc(data.nextURL);
    }
 }
  // var data =        JSON.stringify({"email":"hey@mail.com","password":"101010"});
  xhr.send(data);
 }
 function createRadioElement(name, checked) {
  var radioHtml = '<input type = "radio" name="' + name + '"';
  if ( checked ) {
  radioHtml += ' checked="checked"';
  }
  radioHtml += '/>';
  var radioFragment = document.createElement('div');
  radioFragment.innerHTML = radioHtml;
 return radioFragment.firstChild;
 }

我只是猜测,因为您在发布的代码中有一些东西甚至不会运行,但是createRadioElement返回一个您从未实际注入文档的分离节点。

document.body.appendChild(createRadioElement());