jquery 无法从JavaScript循环调用函数以绑定(通过addEventEvent)到链接

lymnna71  于 2023-11-17  发布在  jQuery
关注(0)|答案(1)|浏览(92)

请参阅JSFiddle
Javascipt:

// Add your code here
LoadQuestion(1);

function LoadQuestion(questionId) {
  console.log('questionId ' + questionId)
  var data;
  if (questionId == 1){ //usually data comes from API
    data = {
      "Options": [
          {
              "OptionId": 2,
              "OptionText": "Application",
              "OptionType": "Link"
          },
          {
              "OptionId": 3,
              "OptionText": "License",
              "OptionType": "Link"
          }
      ],
      "QuestionText": "Hello, select one option",
      "QuestionType": "List"
  };

  } else if (questionId == 2 || questionId == 3){
    data = {
    "Options": [
          {
              "OptionId": 4,
              "OptionText": "Enter Date of birth.",
              "OptionType": "Date"
          },
          {
              "OptionId": 5,
              "OptionText": "Enter last four digits of SSN.",
              "OptionType": "Number"
          },
          {
              "OptionId": 6,
              "OptionText": "Enter your last name.",
              "OptionType": "Text"
          }
      ],
      "QuestionText": "License",
      "QuestionType": "Link"
    };
  }

  const defMsg = document.createElement("div");
  defMsg.append(document.createTextNode(data.QuestionText));
  defMsg.append(generateList(data.Options));
  appendChatMesage(defMsg)

}

function appendChatMesage(content) {
  console.log(content)
  $('#chat-body').append(content);
}

function generateList(jsonArray) {
            var ul = document.createElement('ul');

            // Loop through the JSON array
            for (var i = 0; i < jsonArray.length; i++) {
                var item = jsonArray[i];
                var li = document.createElement('li');
                if (item.OptionType == 'Link') {
                   //alert(JSON.stringify(item));

                    var link = document.createElement('a');

                    link.addEventListener("click", function () {
                        LoadQuestion(item.OptionId);
                    });
                    link.setAttribute('href', '#');
                    link.innerText = item.OptionText;
                    li.appendChild(link);

                    ul.appendChild(li);
                } else if (item.OptionType == 'Date') {
                    //alert(JSON.stringify(item));
                    // Create the table dynamically
                    var dynamicTable = document.createElement("table");
                    dynamicTable.setAttribute("border", "1");
                    var initialRow = dynamicTable.insertRow(0);
                    var cell1 = initialRow.insertCell(0);
                    var cell2 = initialRow.insertCell(1);
                    cell1.innerHTML = item.OptionText;
                    cell2.innerHTML = '<input type="text">';

                     li.appendChild(dynamicTable);
                    ul.appendChild(li);
                }
            }

            return ul;
        }`

字符串
LoadQuestion是入口点,它创建并传递带有div标签的数据到另一个函数(appendChatMesage)。第一次尝试将加载超链接,用户将单击其中一个链接,它应该将相应的问题ID传递给LoadQuestion(以便我们可以传递给API,它返回问题2的详细信息)
问题:第74行,我将一个函数绑定到一个动态创建的超链接,但是数组中最后一个元素将绑定到两个元素上。基本上,LoadQuestion将获得相同的参数,而不管数组中的元素是什么。
我尝试创建超链接与硬coed函数调用像link.click = 'LoadQuestion(' + item.OptionId + '),但没有工作,并给出错误,LoadQuestion找不到.

new9mtju

new9mtju1#

我对你的代码进行了一点重构--主要的一点是,返回给定Option的元素的函数是它自己的函数,所以绑定肯定在正确的范围内。
不再使用jQuery

function getQuestion(questionId) {
  if (questionId === 1) {
    //usually data comes from API
    return {
      Options: [
        {
          OptionId: 2,
          OptionText: "Application",
          OptionType: "Link",
        },
        {
          OptionId: 3,
          OptionText: "License",
          OptionType: "Link",
        },
      ],
      QuestionText: "Hello, select one option",
      QuestionType: "List",
    };
  }
  if (questionId === 2) {
    return {
      Options: [],
      QuestionText: "Application?",
      QuestionType: "Link",
    };
  }
  if (questionId === 3) {
    return {
      Options: [
        {
          OptionId: 4,
          OptionText: "Enter Date of birth.",
          OptionType: "Date",
        },
        {
          OptionId: 5,
          OptionText: "Enter last four digits of SSN.",
          OptionType: "Number",
        },
        {
          OptionId: 6,
          OptionText: "Enter your last name.",
          OptionType: "Text",
        },
      ],
      QuestionText: "License",
      QuestionType: "Link",
    };
  }
  throw new Error("Invalid questionId");
}

function LoadQuestion(questionId) {
  console.log("questionId " + questionId);
  const data = getQuestion(questionId);
  const message = document.createElement("div");
  message.append(document.createTextNode(data.QuestionText));
  message.append(generateList(data.Options));
  document.getElementById("chat-body").appendChild(message);
}

function getOptionForLi(item) {
  const li = document.createElement("li");
  if (item.OptionType === "Link") {
    const link = document.createElement("a");

    link.addEventListener("click", function () {
      LoadQuestion(item.OptionId);
    });
    link.setAttribute("href", "#");
    link.innerText = item.OptionText;
    li.appendChild(link);
    return li;
  }
  if (item.OptionType === "Date") {
    const table = document.createElement("table");
    table.setAttribute("border", "1");
    const initialRow = table.insertRow(0);
    const cell1 = initialRow.insertCell(0);
    const cell2 = initialRow.insertCell(1);
    cell1.innerHTML = item.OptionText;
    cell2.innerHTML = '<input type="text">';
    li.appendChild(table);
    return li;
  }
  li.appendChild(document.createTextNode(JSON.stringify(item)));
  return li;
}

function generateList(jsonArray) {
  var ul = document.createElement("ul");
  for (const item of jsonArray) {
    ul.appendChild(getOptionForLi(item));
  }
  return ul;
}

LoadQuestion(1);

个字符

相关问题