JavaScript 不读取 HTML 输入值

问题描述 投票:0回答:1

在我的主网站

website.com
上,我有一个正在运行的 JS 函数,它从我的 HTML 表单中获取
input
值 - 对是或否问题的响应。然后它通过
switch
语句处理该输入值。我想在我的移动浏览器子域上模拟该功能,
m.website.com
。然而,完全相同的 JS 代码,从相同的 HTML 代码中读取,会为我的
undefined
返回一个
x
值。

有人能明白为什么它不能正确读取值吗?请注意,我知道该功能正在正确触发,因为一旦我选择任何值,我就会收到默认警报。

HTML:

<div>
     <label for="rsvp">Will you be joining us?<br></label>
     <select id="rsvp" name="rsvp" onchange="didTheySayYes()" required> <!-- Function didTheySayYes() triggers follow-up questions as needed -->
     <option value="null"></option>
     <option value="1">Yes, I/we will be there!</option>
     <option value="0">Sorry, I/we can't make it...</option>
     </select>
</div>

JS:

function didTheySayYes() {
    let x = document.getElementById('rsvp').value;               //Extract answer value
    if (x == 'null') {                                           //Don't respond to empty option
        return
    }
    alert(x);
    switch (Number(x)) {
    case 0:                                                       //Response to 'not joining'
        let name1 = document.createElement('div');
        name1.id = 'rsvp_no';
        name1.className = 'RSVPyesorno';
        document.getElementById('rsvp').insertAdjacentElement('afterend', name1);
        name1.innerHTML = `We're sorry you won't be there!<br><label for="name1">Name:<br></label>
        <input type="text" id="name1" name="name1" required>`;
        break;
    case 1:                                                        //Response to 'will join'
        let some = document.createElement('div');
        some.className = 'RSVPyesorno';
        document.getElementById('rsvp').insertAdjacentElement('afterend', some);
        some.innerHTML =`<br><label for="groupsize">With how many people?<br></label>
                        <select id="groupsize" name="groupsize" onchange="RSVPsize()" required>
                            <option value="null"></option>
                            <option value="gs1">1</option>
                            <option value="gs2">2</option>
                            <option value="gs3">3</option>
                            <option value="gs4">4 or more</option>
                        </select>`;                        
        break;
    default:
        alert("Error! Please refresh the page and try again, and if you keep having issues, contact the organizer.");
        break;
    }
}
javascript html input user-input
1个回答
0
投票

如果函数 did TheySayYes() 在您的主网站上正常工作,但在您的子域上却无法正常工作,并且假设两者的 HTML 相同,则问题不太可能出在 JavaScript 代码本身上。相反,它可能与代码在子域上的执行或加载方式有关。

© www.soinside.com 2019 - 2024. All rights reserved.