简体   繁体   English

如何在Javascript中获取属性的值

[英]How to get the value of an attribute in Javascript

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-font but the function getAttribute("value") returns null .函数getAttribute("class")工作正常,它返回card-input small-font但函数getAttribute("value")返回null I tried .value as well but this returns an empty string.我也试过 .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;
}

Node values and Element Attributes are different parts of an html tag. 节点值元素属性是 html 标签的不同部分。 So, you have to use element.value instead.因此,您必须改用element.value

This is a an example, to show you how you can fetch value , data , attribute from 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

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")

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问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM