gpt4 book ai didi

javascript - 从段落内的选择中获取选定的值

转载 作者:行者123 更新时间:2023-12-02 17:04:11 24 4
gpt4 key购买 nike

我在段落中有一个选择,想知道所选值是什么,但我得到空...有什么帮助吗?这是代码:

divWithInfo = document.createElement('div');
divWithInfo.class = 'divWithInfoControls';
divWithInfo.style.position = 'absolute';
divWithInfo.style.top = '10px';
divWithInfo.style.width = '100%';
divWithInfo.style.textAlign = 'center';
var groupToDisplay = '<p id="pSelectGroup" style="display: block;">Select the user group: ';
groupToDisplay += '<select id="selectGroup" onchange="applyGroupSelection()">';
groupToDisplay += '<option selected>Nothing selected</option>';
for ( var g in userGroups )
groupToDisplay += '<option>' + g + '</option>';
groupToDisplay += '</select></p>';
divWithInfo.innerHTML += groupToDisplay;
console.log ( document.getElementById( "selectGroup" ) );

当我应用 onchange 函数时,“document.getElementById”工作正常,只是在这种情况下我得到了 null

最佳答案

看起来您尚未将 divWithInfo 附加到 #document,因此 getElementById 无法在 DOM 中找到它树

在调用 document.getElementById("selectGroup") 之前,请记住,例如document.body.appendChild(divWithInfo)

如果这不是一个选项,您可能需要考虑使用 divWithInfo.querySelector,即

var foo = divWithInfo.querySelector("#selectGroup");

但是,我会尽力避免这种情况,如果在附加之前需要引用,我将完全使用 DOM 方法来创建,并且不使用 .innerHTML

关于javascript - 从段落内的选择中获取选定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25411617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com