我发现了一个奇怪的效果,我无法理解。您需要控制台@jsfiddle 才能看到一些文字
首先测试这个(使用类): https : //jsfiddle.net/ojg1Lzrk/1/set/get with element.value 或 attribute.nodeValue 没有区别。
<input id="i" value="" class="A">
document.addEventListener('DOMContentLoaded', function(event) {
//1) OK - should display A in console
console.log('1)should be A:', i.className)
//2) OK - input field should have B class
i.className = 'B'
//3) OK - should display B in console
console.log('3)should be B:', i.attributes.class.nodeValue)
//4) OK - input field should have C class
i.attributes.value.nodeValue = 'C'
})
下一个测试(使用值): https ://jsfiddle.net/6ya98njL/2/ 现在它不是同步 element.value 有“当前”值和 attribute.nodeValue 是“冻结”并且连接丢失
<input id="i" value="A" oninput="inp()">
document.addEventListener('DOMContentLoaded', function(event) {
//1) OK - should display A in console
console.log('1)should be A:', i.value)
//2) OK - input field should be B
i.value = 'B'
//3) !!! - should display B in console
console.log('3)should be B:', i.attributes.value.nodeValue)
//4) !!! - input field should be C
i.attributes.value.nodeValue = 'C'
})
function inp() {
//5) !!! - different values
console.log('5)inp start', i.value, i.attributes.value.nodeValue)
//6) !!! no change to input field:
i.attributes.value.nodeValue = 'Z'
//7) !!! - different values
console.log('7)inp end', i.value, i.attributes.value.nodeValue)
}
我发现 element.value 和 attribute.nodeValue 是同步的,只要你不设置 element.value 或输入值。之后它就丢失了。但是之前用 attribute.nodeValue 改变是没有问题的。
为什么在这里 class 和 value 之间存在这种差异?即使我在浏览器/检查器中更改类,它也是同步的并且始终工作。
我找到了这个关于价值的答案: Element.value 和 Element.getAttribute("value") 之间的区别
所以问题是:为什么???!!!