我无法弄清楚为什么.value不起作用。我也试过.querySelector而不是.getElementById,但我一直在控制台中得到未定义。无法通过.value从输入中获取值
var submit = document.querySelector('#submit');
var name = document.getElementById('ship-name');
submit.onclick = function() {
console.log(name.value);
};
<div class="box">
<h2>Where do you want your stuff sent?</h2>
<label for="ship-name">
<input class="full text-input" id="ship-name" type="text" placeholder="Name" required>
</label>
<label for="ship-add-1">
<input class="full text-input" id="ship-add-1" type="text" placeholder="Address Line 1" required>
</label>
<label for="ship-add-2">
<input class="full text-input" id="ship-add-2" type="text" placeholder="Address Line 2" required>
</label>
<label for="ship-add-3">
<input class="full text-input" id="ship-add-3" type="text" placeholder="Address Line 3" required>
</label>
<label for="ship-4">
<input class="full text-input" id="ship-add-4" type="text" placeholder="Address Line 4" required>
</label>
</div>
哪里有一个ID为'submit'的元素? – j08691
您无法在全局范围内创建名为'name'的变量。这将是对'window.name'的引用,它总是一个字符串。 –
当我在SO中运行代码片段时,它会抛出一个错误,提示您无法设置属性'onclick'为空 - 也许这与它有关? – Zac