Javascript 如何在Javascript中获取属性的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37880165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:50:48  来源:igfitidea点击:

How to get the value of an attribute in Javascript

javascriptgetattribute

提问by Tamara Caligari

I have this input line which I am trying to extract the text of the value attribute:

我有这个输入行,我试图提取 value 属性的文本:

<input type="text" class="card-input small-font" ng-value="paymentVia.typeDisplay" readonly="" value="Credit card">

The function getAttribute("class")works fine and it returns card-input small-fontbut the function getAttribute("value")returns null. I tried .value as well but this returns an empty string.

该函数getAttribute("class")工作正常并返回,card-input small-font但该函数getAttribute("value")返回null。我也试过 .value ,但这会返回一个空字符串。

Does anyone know why this is happening?

有谁知道为什么会这样?

This is my JS:

这是我的JS:

function() {
   var x = document.getElementsByClassName("card-input small-font");
   var payment =x[18].value;

   return payment;
}

回答by samayo

Node valuesand Element Attributesare different parts of an html tag. So, you have to use element.valueinstead.

节点值元素属性是 html 标签的不同部分。所以,你必须element.value改用。

This is a an example, to show you how you can fetch value, data, attributefrom an input field.

这是一个例子,向你展示了如何获取valuedataattribute从输入字段。

The HTML input field.

HTML 输入字段。

<input type="text" id="profile" data-nationality="Eritrean" value="Simon">

and the javascript.

和 javascript。

var el = document.getElementById("user-profile"); 

console.log(el.value) // Simon
console.log(el.getAttribute("id")) // profile
console.log(el.dataset.nationality) // Eritrean

回答by gurvinder372

element.getAttribute("value")returns value which was set in the markup, which is not necessarily same as element.value.

element.getAttribute("value")返回在标记中设置的值,它不一定与element.value.

Also, value attribute of an element is only synchronized one way- from markup to the object and vice versa doesn't happen.

此外,元素的 value 属性仅以一种方式同步- 从标记到对象,反之亦然不会发生。

So, if you want to get the value that is set programmatically, you need to write

所以,如果要获取以编程方式设置的值,则需要编写

element.value

else, if you need to get the value which was defined in the markup as

否则,如果您需要获取在标记中定义的值

<input value="abc">

you need to do element.getAttribute("value")

你需要做 element.getAttribute("value")

回答by Hardik Vaghani

OR with jQuery you can get value from textbox like

或者使用 jQuery,您可以从文本框中获取价值,例如

var val1 = $(".class name").val();//to get value by class name
var val1 = $("#id").val();//to get value by id

Both will do same.

两者都会做同样的事情。

Regards

问候