gpt4 book ai didi

javascript - HTML输入范围的值,getattribute vs value

转载 作者:行者123 更新时间:2023-11-29 18:11:29 25 4
gpt4 key购买 nike

我已经创建了 type="RANGE"和 id="slider"的 HTML INPUT 元素。为什么我不能使用 getAttribute("value") 方法访问它的值?调试器显示有一个名为“value”的属性,其值不等于元素的值。 range元素的值不应该是它的属性吗?

var sliderValue1=document.getElementById("slider").getAttribute("value");
var sliderValue2= document.getElementById("slider").value;

最佳答案

Why cannot I access its value using getAttribute("value") method?

你不能那样做,因为,.getAttribute("value")返回写入 html 的元素的值(如果您不更改它,则为默认值)。

例子:

与:<input type="range" id="slider" value="500">

document.getElementById("slider").getAttribute("value");返回 500如果您使用输入更改范围。

Debugger shows that there is an attribute named "value" with some value which is not equal to the value of the element.

这是真的,而且是对的。如果您设置默认值,它永远不会改变(对于重置输入很有用)。

Should not the value of range element be its attribute?

不,元素的当前值存储在 html 之外,因此要访问当前值,您必须使用:document.getElementById("slider").value; , 但不仅在范围上,所有类型的输入都是一样的。

$(function(){
$("input[name=foo]").on("change",function(){
var val = $(this).val();
var attr = $(this).attr("value");
var prop = $(this).prop("value");
console.log(" --- JQUERY TEST JS ----");
console.log("Current value: (using .val)",val);
console.log("Initial value: (using .attr)",attr);
console.log("Current value: (using .prop)",prop);
});
});

//NATIVE JS
function originalJS(){
console.log(" --- ORIGINAL JS ----");
console.log("Current value: (using .value)",this.value);
console.log("Initial value: (using .attr)",this.getAttribute("value"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="range" onChange="originalJS.call(this)" name="foo" value="500"/>
<p>RUN AND WATCH CONSOLE :) ... watch value="500" (but range is 0-100)</p>

<input type="text" onChange="originalJS.call(this)" name="foo" value="500"/>

关于javascript - HTML输入范围的值,getattribute vs value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27013633/

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