다음과 같이 만든 선택 요소를 동적으로 만드는 버튼이 있습니다.
var units = units_array[0];
//ingredient unit of measurement drop down
var cell3= row.insertCell(2);
var unit_of_measure = document.createElement("select");
unit_of_measure.name = "unit_of_measure_select";
cell3.appendChild(unit_of_measure);
//Create and append the options
for (var i = 0; i < units.length; i++) {
var option = document.createElement("option");
option.value = units[i];
option.text = units[i];
unit_of_measure.appendChild(option);
}
그러나 내부 (다른 함수의 루프 내부)를 선택하면 콘솔에서 다음 오류가 발생합니다.
포착되지 않은 TypeError : 정의되지 않은 'undefined'속성을 읽을 수 없습니다.
다음은 테이블 내부에있는 선택 요소를 가져 오는 데 사용하는 코드입니다.
var table = document.getElementById('selected_ingredients');
var rowCount = table.rows.length; //empty table has 2 rows (header + something else?)
var cellsCount = table.rows[0].cells.length -1 ; //table width in cells by counting headers minus the last cell (delete)
for (var r = 1; r < rowCount; r++) { //loop through all rows (r) in table
var $ingredient_dict = {}; //initiate dictionary for this ingredient
for (var c = 0; c < cellsCount; c++) { //loop through each cell (c) in row
var $cell = table.rows[r].cells[c];
if ($cell.innerHTML.includes("select")) { //if its is 3rd iteration (3rd cell along = select box)
alert("test");
//not working - undefined value from generated select element
var UOM = $cell.options[$cell.selectedIndex].value;
alert(UOM);
var UOM에서 선택한 옵션의 값을 반환하고 싶습니다. 나는 js에 비교적 익숙하지 않으므로 이것이 간단하다면 사과드립니다.
if 문에서 select 요소에 대한 핸들을 잡을 수 있습니다.
$select = $cell.querySelector('select');
//then to grab the option and value
var UOM = $select.selectedOptions[0].value;
alert(UOM);
또한 innerHTML의 텍스트를 확인하는 대신 if 문에서 다음을 수행하는 것이 좋습니다.
$cell.querySelector('select');
이것은 선택 요소가 없으면 false와 동등한 null을 반환하지만 요소가 있으면 true를 반환합니다. 장점은 셀 중 하나에 'select'라는 단어가 포함되어 있으면 문자열 'select'를 확인하는 경우 true를 반환하고 존재하지 않는 요소를 선택하려고 시도하지만 방금 찾은 요소입니다. 도움이 되었기를 바랍니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다